简体   繁体   English

在 useEffect 中使用 React Context Dispatch 时出现无限循环

[英]Getting infinite loop when using React Context Dispatch in useEffect

I'm working on a project and created a context that is supposed to store my projects data.我正在处理一个项目并创建了一个应该存储我的项目数据的上下文。 I included the context dispatch inside of a useEffect in a component which is supposed to pass the data object to the context but I am running into an issue where I am an infinite loop.我将上下文调度包含在一个组件中的 useEffect 中,该组件应该将数据 object 传递给上下文,但我遇到了一个问题,我是一个无限循环。 I completely simplified the structure and I still can't figure out what my problem is.我完全简化了结构,但我仍然无法弄清楚我的问题是什么。 I pasted the code below.我粘贴了下面的代码。 Does anyone know what I could be doing wrong?有谁知道我可能做错了什么?

// DataContext.js
import React, { useReducer } from "react";

export const DataContext = React.createContext();

const dataContextInitialState = { test: 1 };

const dataContextReducer = (state, action) => {
  switch (action.type) {
    case "update":
      console.log(state);
      return {
        ...state,
        action.value,
      };

    default:
      return dataContextInitialState;
  }
};

export const DataContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(
    dataContextReducer,
    dataContextInitialState
  );

  return (
    <DataContext.Provider
      value={{
        state,
        dispatch,
      }}
    >
      {children}
    </DataContext.Provider>
  );
};

// Component that is accessing context

    .
    .
    .
  useEffect(() => {
    dataContext.dispatch({
      type: "update",
    });
  }, [dataContext]);
    .
    .
    .

I think this happens because the useEffect gets called during the first render, it executes dispatch that calls your reducer which returns a new object { dataContextInitialState } .我认为这是因为useEffect在第一次渲染期间被调用,它执行调用你的减速器的dispatch ,它返回一个新的 object { dataContextInitialState }

The new obect is passed down to your component, useEffect checks if the dataContext object is the same as in the previous render, but it is different because it's a new object so it re-executes the useEffect and you have the loop.新的对象被传递给你的组件, useEffect检查dataContext object 是否与之前的渲染相同,但它不同,因为它是一个新的 object 所以它重新执行useEffect并且你有循环。

A possible solution一个可能的解决方案

From my understanding with this piece of code根据我对这段代码的理解

const dataContextInitialState = { test: 1 };

case "update":
  return {
    dataContextInitialState,
  };

your state becomes this:你的 state 变成这样:

{
  dataContextInitialState: {
    test: 1
  }
}

I guess that what you wanted was to have a state which is an object with a key names test , you can try modifying your code like this:我猜你想要的是拥有一个 state ,它是一个带有键名test的 object ,你可以尝试像这样修改你的代码:

case "update":
  return dataContextInitialState;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM