1. 需要⼀个store来存储数据
2. store⾥的reducer初始化state并定义state修改规则
3. 通过dispatch⼀个action来提交对数据的修改
4. action提交到reducer函数⾥,根据传⼊的action的type,返回新的
state
创建store,src/store/ReduxStore.js
import {createStore} from 'redux'
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'add':
return state + 1
case 'minus':
return state - 1
default:
return state
}
}
const store = createStore(counterReducer)
export default store
创建ReduxPage
import React, { Component } from "react";
import store from "../store/ReduxStore";
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 变更订阅