在React项目中添加Redux

在React项目中添加Redux,第1张

在React项目中添加Redux

首先,您需要通过或将 reduxreact-redux 软件包安装到项目中。

npm``yarn

您只需使用一行代码即可安装它们:

npm install redux react-redux --save

或与纱线:

yarn add redux react-redux

现在返回项目并使用以下名称创建3个文件:

action.js
reducer.js
store.js

打开

action.js
文件。我们应该为此应用程序执行两个 *** 作。一种用于增加,另一种用于减少。

action.js中

const INCREMENT_COUNTER = 'INCREMENT_COUNTER';const DECREMENT_COUNTER = 'DECREMENT_COUNTER';const increment = () => ({type: INCREMENT_COUNTER});const decrement = () => ({type: DECREMENT_COUNTER});export {  INCREMENT_COUNTER,  DECREMENT_COUNTER,  increment,  decrement}

动作是简单的函数,从组件分派到redux,用于

store
通过化简器更改状态)。

所以我们应该更改 reducer.js

import {INCREMENT_COUNTER, DECREMENT_COUNTER} from "./action";const initialState = {  counter: 0};const reducer = (state = initialState, action) => {  switch (action.type) {    case(INCREMENT_COUNTER):      return {        ...state,        counter: state.counter + 1      };    case (DECREMENT_COUNTER):      return {        ...state,        counter: state.counter - 1      };    default:      return state  }};export default reducer

使用redux的3条主要原则:

1-真理的单一来源。整个应用程序的状态存储在单个存储中的对象树中。

2-状态为只读。更改状态的唯一方法是发出一个动作,一个描述发生了什么的对象。

3-使用纯功能进行更改。

根据第二个原则,我们必须假定状态是不可变的,并且每种情况(在开关中)都必须单独返回状态。在返回状态中使用…
state表示如果initialState将来会更改,则这些情况将正常工作(在此示例中,这是没有必要的)。

我们的行动职能是纯粹的(第三原则)

最后一个新文件 store.js

import {createStore} from "redux";import reducer from './reducer'const store = createStore(reducer);export default store;

现在我们应该将此商店应用于我们的App组件。因此,打开App.js文件并进行以下更改:

App.js中

import React, {Component} from 'react';import CounterApp from './CounterApp'import {Provider} from 'react-redux'import store from './store'class App extends Component {  render() {    return (      <Provider store={store}>        <CounterApp/>      </Provider>    );  }}export default App;

提供包裹的

CounterApp
组成部分,将传播
store
App
CounterApp
所有其他的子组件。

最后,更改 CounterApp.js

import React, {Component} from 'react';import {connect} from "react-redux";import {increment, decrement} from "./action";class CounterApp extends Component {  handleIncrement = () => this.props.dispatch(increment());  handleDecrement = () => this.props.dispatch(decrement());  render() {    return (      <div>        <button onClick={this.handleIncrement}>Increment</button>        <p>{this.props.counter}</p>        <button onClick={this.handleDecrement}>Decrement</button>      </div>    );  }}const mapStateToProps = state => {  const counter = state.counter;  return {counter}};export default connect(mapStateToProps)(CounterApp);

我们正在使用

increment
decrement
*** 作将 *** 作分派到redux。

state
被删除,而不是状态中,我们创建一个特殊的功能
mapStateToProps' and use
connect`的状态连接组件的道具。

大功告成!



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4983684.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存