問題描述
如何在 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?
參考解法
方法 1:
You can combine createContext
and useReducer
like this:
const StoreContext = React.createContext();
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StoreContext.Provider value={{ state, dispatch }}>
<Content />
</StoreContext.Provider>
);
}
Inside your components you could then use useContext(StoreContext)
to get access to your state
and dispatch
.