1、在项目中安装redux插件
npm install redux -S
2、针对单独的view组件定义store状态存储对象,参数为对状态的更新操作函数
import { createStore } from 'redux';
const reducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT': return state > 0 ? state - 1 : state;
default: return state;
}
};
const store = createStore(reducer);
export default store;
3、在view组件中引入store状态存储对象,并且在constructor中监听状态的变化,更新view上的数据
import React, { Component } from 'react';
import store from './store'; //引入状态对象
class App extends Component {
constructor(props){
super(props);
this.state = {
count:store.getState() //获取状态数据
}
store.subscribe(() => { //监听状态变化更新数据
this.setState({
count:store.getState()
})
})
}
onIncrement = () => { //分发状态更新
store.dispatch({
type:'INCREMENT'
})
}
onDecrement = () => { //分发状态更新
store.dispatch({
type:'DECREMENT'
})
}
render() {
return (
<div>
<h1>{this.state.count}</h1> <!--展示数据-->
<button onClick={this.onIncrement}>+</button>
<button onClick={this.onDecrement}>-</button>
</div>
);
}
}
export default App;