使用action与reducer

这里主要研究通过action(借书人说的话)传递给store(管理员),store再从reducer(记录本)查询数据,reducer将查询到的数据返回给store,最后store再返回给组件(借书用户)。最终要实现当reducers数据发生变化的时候,组件的数据也跟着变化

1.当组件的input框输入内容发生改变时,自动调用handleInputChange,通过store.dispatch()将数据发送给store(管理员)

handleInputChang (e){
        const action = {
            type: 'chang_input_value',
            value: e.target.value
        }
        store.dispatch(action);
    }

2.store会自动将previousState与接收到的action传递给reducers(记录本)

3.reducers接收store传递过来的数据进行判断,如果为真将其新数据返回给store

//reducer可以接收state的数据,但是不可以修改
export default (state = defaultState , action) => {
    if(action.type === 'chang_input_value') {
        const newState = JSON.parse(JSON.stringify(state)) //深拷贝
        newState.inputValue = action.value;
        return newState;
    }
    return state;
}

4.组件订阅store的改变,只要store改变,就触发该方法

//订阅store的改变,只要store改变,就触发该方法
store.subscribe(this.handleStoreChange)

将其写到custructor中

5.将最新的store数据获取到

handleStoreChange () {
        this.setState(store.getState())
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React Context 结合 Reducer 可以实现状态管理和状态更新的功能。Reducer 是一个纯函数,接收当前的状态和一个 action,返回一个新的状态。通过 Context 和 Reducer 的结合使用,可以将状态和状态更新逻辑分离到不同的文件,使得组件的代码更加简洁和清晰。 下面是一个示例代码: ```jsx // 创建一个 context 对象 const MyContext = React.createContext(); // 定义 reducer 函数 function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; default: throw new Error(); } } // 父组件 function ParentComponent() { const [state, dispatch] = useReducer(reducer, { count: 0 }); // 将 reducer 的 dispatch 函数作为属性传递给子组件 return ( <MyContext.Provider value={{ state, dispatch }}> <ChildComponent /> </MyContext.Provider> ); } // 子组件 function ChildComponent() { // 使用 useContext 钩子获取父组件提供的 context 对象 const { state, dispatch } = useContext(MyContext); return ( <div> <p>当前的计数:{state.count}</p> <button onClick={() => dispatch({ type: "increment" })}>增加</button> <button onClick={() => dispatch({ type: "decrement" })}>减少</button> </div> ); } ``` 在上面的代码,父组件使用 `useReducer` 钩子创建了一个状态以及一个 dispatch 函数。将状态和 dispatch 函数通过 Context 提供给子组件。在子组件,通过 `useContext` 钩子获取父组件提供的 state 和 dispatch 对象。当用户点击子组件的增加或减少按钮时,会调用 dispatch 函数并传入对应的 action 对象,从而触发状态更新,更新后的状态会自动传递给所有使用了该 Context 的组件,实现了状态的管理和更新。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值