首先,您需要通过或将redux和react-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更改(状态)的简单函数。
所以我们应该改变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- 使用纯函数进行更改。
根据第二个原则,我们必须假设状态是不可变的,并且每个 case(在 switch 中)必须单独返回状态。在返回状态中使用 ...state 意味着如果 initialState 将来会发生变化,这些情况将正常工作(在本例中没有必要)。
我们在行动中的功能是纯粹的(第三原则)
和最后一个新文件store.js:
import {createStore} from "redux";
import reducer from './reducer'
const store = createStore(reducer);
export default store;
现在我们应该将这个 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;
Provider 包装了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`的状态连接组件的props。
大功告成!