【问题标题】:How can you replace Redux by the react ContextAPI in a Django App如何在 Django 应用程序中用 react ContextAPI 替换 Redux
【发布时间】:2019-09-04 07:49:20
【问题描述】:

我最近学会了如何使用 createContext() 来模仿 redux 的行为。我知道如何使用 react contextAPI 和 react hooks。但是现在,我尝试连接 django 和 react,但是每个教程都提到了 Redux。如何用 createContext + react hooks 替换 Redux?

【问题讨论】:

  • 你能提供一些你尝试过的代码示例吗?
  • @iofjuupasli 抱歉,这是一个悬而未决的问题

标签: django reactjs redux react-context


【解决方案1】:

您可以像这样组合createContextuseReducer

const StoreContext = React.createContext();

const App = () => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <StoreContext.Provider value={{ state, dispatch }}>
      <Content />
    </StoreContext.Provider>
  );
}

在您的组件中,您可以使用useContext(StoreContext) 来访问您的statedispatch

【讨论】:

  • 谢谢!我得试试这个。如果我对这种方法有点迷茫,我会告诉你
猜你喜欢
  • 2019-02-07
  • 2023-03-17
  • 1970-01-01
  • 2017-11-22
  • 1970-01-01
  • 2016-06-04
  • 2016-08-10
  • 2016-12-11
  • 2016-11-09
相关资源
最近更新 更多