如何用 Django 应用程序中的 React ContextAPI 替换 Redux
How can you replace Redux by the react ContextAPI in a Django App
我最近学习了如何使用 createContext() 来模仿 redux 行为。我知道如何使用 react contextAPI 和 react hooks。但是现在,我尝试连接 django 和 react,但每个教程都提到 Redux。如何用 createContext + react hooks 替换 Redux?
您可以像这样组合 createContext
和 useReducer
:
const StoreContext = React.createContext();
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StoreContext.Provider value={{ state, dispatch }}>
<Content />
</StoreContext.Provider>
);
}
在您的组件中,您可以使用 useContext(StoreContext)
访问您的 state
和 dispatch
。
我最近学习了如何使用 createContext() 来模仿 redux 行为。我知道如何使用 react contextAPI 和 react hooks。但是现在,我尝试连接 django 和 react,但每个教程都提到 Redux。如何用 createContext + react hooks 替换 Redux?
您可以像这样组合 createContext
和 useReducer
:
const StoreContext = React.createContext();
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StoreContext.Provider value={{ state, dispatch }}>
<Content />
</StoreContext.Provider>
);
}
在您的组件中,您可以使用 useContext(StoreContext)
访问您的 state
和 dispatch
。