首先,您需要通过npm 或yarn 将redux 和react-redux 包安装到您的项目中。
你可以用一行代码简单地安装它们:
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
}
actions 是从组件分发到 redux 的简单函数
用于通过 reducers 更改 store(state)。
所以我们应该改变 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(in switch) 必须单独返回状态。
在返回的状态中使用 ...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;
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 useconnect` 来代替 state,将 state 连接到组件 props。
大功告成!