【问题标题】:How to use React Context API with useReducer to follow a similar style to Redux [closed]如何将 React Context API 与 useReducer 一起使用以遵循与 Redux 类似的风格 [关闭]
【发布时间】:2021-12-20 08:26:10
【问题描述】:

我知道如何使用上下文 API,但我正在尝试以另一种方式使用它,这与 Redux 的工作方式非常相似,因此当我尝试学习它时,我可以更好地使用 Redux。对于这个简单案例,我的目标是在输入字段中输入内容并将其呈现到屏幕上,如果您单击按钮,则会出现一个警报窗口,显示您输入的内容。如果单击明文,则输入字段将为空白。我希望能够做到这一点,而不必求助于 useState 之类的本地状态管理,而是调度我在 reducers 文件中创建的方法并提取状态值。我不能做第二部分,看起来我正在正确调度,但是当我尝试渲染“文本”时,它只是渲染初始状态,我不知道如何更新它,甚至不知道如何清除文本。这是我的沙箱的链接: https://codesandbox.io/s/create-context-api-redux-style-odv01?file=/src/Button.js

【问题讨论】:

    标签: javascript reactjs redux react-context


    【解决方案1】:

    我不会重写您的所有代码,但我可以指出您的问题所在,以便您继续处理。您的问题在于您创建的上下文提供程序,它永远不会更新状态。上下文提供者负责将状态直接分配给整个树中的子组件,但它仍然需要保持该状态,在您的情况下,您没有为它定义任何状态。

    import React, { createContext, useContext, useReducer } from "react";
    
    export const StateContext = createContext({
      // put your initial state here
    });
    
    // then this will now have initial state and updated state
    export const useStateValue = () => useContext(StateContext);
    
    export const StateProvider = ({ reducer, initialState, children }) => (
      // now you can declare state like this
      const [example1, setExample1] = useState(example1)
      const [example2, setExample2] = useState(example2)
      // this is where you'll define your dispatch function
    
      // and use it like this
      const value = {
        example,
        setExample,
        example2,
        setExample2
        // or you can add a custom dispatch here
      }
    
      <StateContext.Provider value={value}>
        {children}
      </StateContext.Provider>
    
      // or you can do
      const [example, setExample] = useState(useStateValue())
    
      <StateContext.Provider value={{example, setExample}>
        {children}
      </StateContext.Provider>
    );
    

    这段代码并不完美,它只是为了让您了解应该做什么。现在,当您在某处导入 useStateValue 时,您可以选择如何销毁它以及要导入哪些状态/函数,即调度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 2021-07-09
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多