【问题标题】: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
【问题描述】:
【问题讨论】:
标签:
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 时,您可以选择如何销毁它以及要导入哪些状态/函数,即调度。