浅谈redux如何修改仓库的值和将组件拆分为容器组件和ui组件

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} />
    }
}
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值