export default class ReduxPage extends Component {
componentDidMount() {
store.subscribe(() => {
console.log("subscribe");
this.forceUpdate();
//this.setState({});
});
}
add = () => {
store.dispatch({ type: "add" });
};
minus = () => {
store.dispatch({ type: "minus" });
};
stayStatic = () => {
store.dispatch({ type: "others" });
};
render() {
console.log("store", store);
return (
<div>
<h1>ReduxPage</h1>
<p>{store.getState()}</p>
<button onClick={this.add}>add</button>
<button onClick={this.minus}>minus</button>
<button onClick={this.stayStatic}>static</button>
</div>
);
}
}
如果点击按钮不能更新,因为没有订阅状态变更
还可以在src/index.js的render?订阅状态变更
import store from ‘./store/ReduxStore‘
const render = ()=>{
ReactDom.render(
<App/>,
document.querySelector(‘#root‘)
)
}
render()
store.subscribe(render)
检查点
1. createStore 创建store
2. reducer 初始化、修改状态函数
3. getState 获取状态值
4. dispatch 提交更新
5. subscribe 变更订阅