使用带有反应钩子的 redux [英] Using redux with react hooks

查看:52
本文介绍了使用带有反应钩子的 redux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出将 redux 与 react hooks 结合使用的最佳方式.我看到了以下内容

I'm trying to figure out the best way to use redux with react hooks. I saw the following

如何使用 React hooks + Redux

但是我不相信这是最好的方法.有没有人有其他想法?

However I'm not convinced this is the best way to go. Does anyone have any alternative ideas?

我也看到了以下内容,似乎还不错.https://www.npmjs.com/package/redux-react-hook

I also saw the following and seems quite good. https://www.npmjs.com/package/redux-react-hook

谢谢

推荐答案

作为 redux 的替代方案,您可以使用 hooks 来管理状态,您可以使用 context api 和自定义钩子

As an alternative to redux you can use hooks to manage the state, you can create the similar using the combination of context api and custom hooks

const initialState = {
    stateSet: false,
    plan: {
    }
}
const AppReducer = (state = initialState, action) => {
    return {
        plan: planReducer(state.plan, action)
    }
}



const AppProvider = (props) => {

    const [state, dispatch] = useReducer(AppReducer, initialState);
    return (
        <AppStateContext.Provider value={state}>
            <AppDispatchContext.Provider value={dispatch}>
                {props.children}

            </AppDispatchContext.Provider>
        </AppStateContext.Provider>
    )


}

const useAppState = () => {
    const context = React.useContext(AppStateContext);
    return context;
}


const useAppDispatch = () => {
    const context = React.useContext(AppDispatchContext);
    return context;
}

然后在你的组件中,你可以使用任何组件

then inside your component, you can any component

const { plan } = useAppState();
 dispatch({ type: 'updateBusinessInfo', payload: { businessInfo: businessInfo, addOnsInfo: addOnsInfo } });

参考 https://kentcdodds.com/blog/how-to-use-react-context-effectively 来自 kencdoods 的精彩博文,了解详情

refer https://kentcdodds.com/blog/how-to-use-react-context-effectively fantastic post by kencdoods for details

这篇关于使用带有反应钩子的 redux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆