【问题标题】:useReducer not updating the initialState when used with useContext与 useContext 一起使用时,useReducer 不更新 initialState
【发布时间】:2021-06-19 18:59:38
【问题描述】:

我有一个表单,它必须预先填充一些值。这些值来自上下文。我正在使用减速器来处理表单的状态,因此我根据从上下文中获得的信息来设置减速器的初始状态。现在发生的情况是上下文发生了变化,但 reducer 状态没有改变。

const { selectedCurrency } =
        useContext<CurrenciesContextType>(CurrenciesContext);

const [state, dispatch]: [CurrencyReducerState, Dispatch<any>] = useReducer(
    currencyReducer as ReducerWithoutAction<CurrencyReducerState>,
    selectedCurrency,
    init
);

理想情况下,当 selectedCurrency 发生变化时,它应该设置初始值。但它不会发生。知道为什么吗?我已将父组件包装在提供程序中。此外,每次 selectedCurrency 更改时,我都会看到 selectedCurrency 更改但减速器状态不会更改。如果组件被重新渲染,那么 reducer 会拾取更改并正确初始化。有没有办法做到这一点?

【问题讨论】:

  • 第三个参数 init 是一个函数,该函数在哪里定义? init 被称为延迟初始化,我无法从发布的问题中找到 sn-p
  • @Learner const init = (state)=&gt;({...INITIAL_STATE, ...state});

标签: reactjs react-hooks


【解决方案1】:

如果没有更多示例代码,这很难说,但也许您忘记使用上下文提供程序包装您的代码?需要使用上下文(对象和/或回调)的代码需要包装在提供程序中。

return (
  <div className="App">
    {/* CurrenciesProvider enables children to use the context info */ } 
    <CurrenciesProvider>
      <CurrencySelector />
      <CurrencyDisplay />
    </CurrenciesProvider>
  </div>
);

这是一个代码框... https://codesandbox.io/s/kind-noether-zr9dq

【讨论】:

  • 我已将父组件包装在提供程序中。此外,每次 selectedCurrency 更改时,我都会看到 selectedCurrency 更改但减速器状态不会更改。如果组件被重新渲染,那么 reducer 会拾取更改并正确初始化。
  • 然后发布一个代码框来演示这个问题。如果你展示一个失败的例子,帮助修复会更容易。
  • 基本上,只要上下文变量发生变化,我就想重新初始化减速器的初始状态。有可能吗?
【解决方案2】:

我能够通过在我的 reducer 中添加一个 updateState 操作并将此操作包装在 useEffect 中,并将 selectedCurrency 作为其依赖项来实现此行为:

useEffect(() => {
    actions.updateState(selectedCurrency)
}, [selectedCurrency])

下面是动作的样子:

updateState: (updatedState): void => 
    dispatch({type: "update", payload: updatedState})

init() 函数仅在 useReducer 首次调用时执行一次。

类似的问题 - Updating useReducer 'state' using useEffect

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2021-12-22
    • 2021-09-24
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多