我有一个表单,它必须预先填充一些值。这些值来自上下文。我正在使用一个 reducer 来处理表单的状态,所以我根据我从上下文中得到的内容设置了 reducer 的初始状态。现在发生的情况是上下文发生了变化,但减速器状态没有发生变化。
const { selectedCurrency } =
useContext<CurrenciesContextType>(CurrenciesContext);
const [state, dispatch]: [CurrencyReducerState, Dispatch<any>] = useReducer(
currencyReducer as ReducerWithoutAction<CurrencyReducerState>,
selectedCurrency,
init
);
理想情况下,每当 selectedCurrency 发生变化时,它应该设置初始值。但它不会发生。知道为什么吗?我已将父组件包装在提供程序中。此外,每次 selectedCurrency 发生变化时,我都会看到 selectedCurrency 发生变化,但减速器状态没有变化。如果组件被重新渲染,则reducer 会接收更改并正确初始化。有没有办法做到这一点?
答案 0 :(得分:0)
如果没有更多示例代码,很难判断,但也许您忘记用上下文提供程序包装您的代码?需要使用上下文(对象和/或回调)的代码需要包装在提供程序中。
return (
<div className="App">
{/* CurrenciesProvider enables children to use the context info */ }
<CurrenciesProvider>
<CurrencySelector />
<CurrencyDisplay />
</CurrenciesProvider>
</div>
);
这是一个代码沙盒... https://codesandbox.io/s/kind-noether-zr9dq
答案 1 :(得分:0)
我能够通过在我的 reducer 中添加一个 updateState 操作并将该操作包装在 useEffect 中并使用 selectedCurrency 作为其依赖项来实现此行为:
useEffect(() => {
actions.updateState(selectedCurrency)
}, [selectedCurrency])
这是动作的样子:
updateState: (updatedState): void =>
dispatch({type: "update", payload: updatedState})
init() 函数仅在第一次调用 useReducer 时执行一次。