首页 > 其他 > 详细

redux进行研究3

时间:2020-06-30 19:56:01      阅读:55      评论:0      收藏:0      [点我收藏+]
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 变更订阅
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

redux进行研究3

原文:https://www.cnblogs.com/zhouyideboke/p/13215356.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!