使用 useEffect 更新 useReducer 'state' [英] Updating useReducer 'state' using useEffect

查看:52
本文介绍了使用 useEffect 更新 useReducer 'state'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我使用的是 React Hooks/Context API.现在,每当我的 Provider 组件挂载时,我都需要将从 localStorage 获取的数据分配给 initialState.carts/state.carts.如果 useEffect 支持返回对象,这是可能的.但是不能在useEffect中返回对象!

In my application, I am using React Hooks/Context API. Now I need to assign fetched data from localStorage to initialState.carts / state.carts whenever my Provider component did mount. It would possible if useEffect supports returning objects. But it's not possible to return object in useEffect!

现在我该如何解决问题?

Now how can I solve the problem?

代码如下,

const initialState = {
  books: books,
  carts: []
};

export const Context = createContext(initialState);

export const Provider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  useEffect(() => {
    if (localStorage.getItem("carts") !== null) {
      const fetchedCarts = JSON.parse(localStorage.getItem("carts"));
      //Here I want to assign 'fetchedCarts' array items in 'state.carts' or 'initialState.carts'
    }
  });

推荐答案

你必须调度一个动作来更新你的 state 变量.

You have to dispatch an action to update your state variable.

if (localStorage.getItem("carts") !== null) {
      const fetchedCarts = JSON.parse(localStorage.getItem("carts"));
      dispatch({ type: 'UPDATE', payload: fetchedCarts })
}

因此,您必须将此操作类型添加到您已在此处使用的 reducer 开关:

So you have to add this action type to your reducer switch which you already used here:

const [state, dispatch] = useReducer(reducer, initialState);

Reducer 结构示例:

En example of reducer structure:

const reducer = (state, action) => {
  switch (action.type) {
    case 'UPDATE':
      return { ...state, ...action.payload }
      break
    default:
      return state
  }
}

我相信 useEffect() 应该有一个依赖数组(因为 state 的更新会以当前的形式重新触发它).

I believe that useEffect() should have a dependencies array (because the update of state will retrigger it in the current form).

如果 useEffect 支持返回对象是可能的.但是不能在useEffect中返回对象!

It would possible if useEffect supports returning objects. But it's not possible to return object in useEffect!

来自 useEffect 的响应应该是一个函数(该函数在卸载组件之前被调用) - 在这里返回一个对象将是一个错误.

The response from the useEffect should be a function (that function is being called before component is unmounted) - returning a object here would be a mistake.

这篇关于使用 useEffect 更新 useReducer 'state'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆