1,redux如何修改仓库的值
①先分发store.dispatch({type:‘XXX’,n:xxx})
dispatch({type:'XXX',key:value.....})
注:action 一定有type ,还可能接收一些其他参数,type尽量大写,action对象的type值 千万不要重复
动作发给了 reducer 第二个参数 action
②根据type修改数据
a. 做 state 的复本
b. 修改state的复本对象
c. 返回新的state
var newState={...state}; // 复本
newState.n=newState.n+action.p; //修改
console.log(newState.n)
return newState; //返回新状态
③subscribe 监听store里的数据变化
subscribe参数是回调函数
store.subscribe(()=>{})
总结:
组件里 store.dispatch(action(actionCreator)) ---->reducer(type,action) —>复本,修改,返回–》组件里通过store.getState() 取最新的值(subscribe)
2,将组件拆分成ui组件和容器组件
一般来说UI组件 只管渲染,容器组件 和store打交道
UI组件:
class One extends Component {
render() {
let { n,dec,inc } = this.props
return (
<div>
<button onClick={dec}>-</button>
{n}
<button onClick={inc}>+</button>
</div>
)
}
}
容器组件:
class OneContainer extends Component {
constructor(props) {
super(props)
this.state = {
n: store.getState().n
}
//参数是一个函数
store.subscribe(this.change)
}
//当store里数据修改的时候会执行这个回调函数
change = () => {
this.setState({
n: store.getState().n
})
}
dec() {
store.dispatch(actionCreator.decAction(1))
}
inc() {
store.dispatch(actionCreator.incAction(2))
}
render(){
return <One n={this.state.n} inc={this.inc} dec={this.dec} />
}
}