首页 > 解决方案 > ReactJS:在useEffect中获取时超出最大更新深度错误

问题描述

在 React 16.8 中,我使用 useReducer、useContext 挂钩实现了我的项目,并创建了一个与 Redux 类似的全局状态管理系统。

在一个视图中,当我尝试在 useEffect 中获取数据时,它会导致最大更新深度错误。

我已经尝试了Facebook React - Hooks-FAQ中的所有示例,但无法解决问题。

我的 package.json 是这样的:

    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-app-polyfill": "^1.0.1",
    "react-chartjs-2": "^2.7.6",
    "react-dom": "^16.8.6",
    "react-router-config": "^5.0.0",
    "react-router-dom": "^5.0.0",
    "react-test-renderer": "^16.8.6",
    "react-uuid": "^1.0.2",
    "reactstrap": "^7.1.0",
    "simple-line-icons": "^2.4.1",
    "styled-components": "^4.2.0"

这是我的代码示例:

这是 View.js

import React, { useEffect, useRef } from 'react'
import useView from '/store/hooks/useView'
import isEqual from '/services/isEqual'
import loading from '/service/loading'

const View = () => {
    const viewContext = useView()
    let viewContextRef = useRef(viewContext)

    // Keep latest viewContext in a ref
    useEffect(() => {
        viewContextRef.current = viewContext
    })

    useEffect(() => {

        // Fetch Data
        async function fetchData() {
            // This causes the loop
            viewContextRef.current.startFetchProcess()

            const url = 'http://example.com/fetch/data/'

            try {
                const config = {
                    method: 'POST',
                    headers: {
                        Accept: 'application/json',
                        'Content-Type': 'application/json',
                    }
                }

                const response = await fetch(url, config)

                if (response.ok) {
                    const res = await response.json()
                    finalizeGetViewList(res)

                    // This causes the loop
                    viewContextRef.current.stopFetchProcess()

                    return res
                } 
            } catch (error) {
                console.log(error)
                return error
            }
        }

        // Prepare data for rows and update state
        const finalizeGetViewList = (data) => {

            const { Result } = data

            if (Result !== null) {

                let Arr = []

                for (let i = 0; i < Result.length; i++) {
                    let Obj = {}
                    //...
                    //...
                    Arr.push(Obj)
                }

                // I compare the prevState with the fetch data to reduce 
                // the number of update state and re-render, 
                // so this section do not cause the problem

                if (!isEqual(roleContextRef.current.state.rows, Arr)) {
                    viewContextRef.current.storeViewList(Arr)
                }

            } else {
                console.log(errorMessage)
            }
        }

        function doStartFetch () {
                fetchData()
        }

        const startingFetch = setInterval(doStartFetch, 500)
        // aborting request when cleaning
        return () => {
            clearInterval(startingFetch)
        }
    }, [])

    const {
      rows,
      isLoading
    } = viewContext.state

    if (isLoading) {
        return (loading())
    } else {
        return (
          <div>
            {rows.map(el => (
            <tr key={el.id}>
              <td>el.name</td>
              <td>el.price</td>
              <td>el.discount</td>
            </tr>
            ))}
          </div>  
        )
    }
}

export default View

如果您真的愿意解决这个问题,请查看存储周期的其他文件。

这是 useView.js 的钩子:

import { useContext } from 'react'
import { StoreContext } from "../providers/Store"

export default function useUsers() {
  const { state, actions, dispatch } = useContext(StoreContext)

  const startFetchProcess = () => {
    dispatch(actions.viewSystem.startFetchProcess({
      isLoading: true
    }))
  }

  const storeViewList = (arr) => {
    dispatch(actions.viewSystem.storeViewList({
      rows: arr
    }))
  }

  const stopFetchProcess = () => {
    dispatch(actions.viewSystem.stopFetchProcess({
      isLoading: false
    }))
  }

  return {
    state: state.viewSystem,
    startFetchProcess,
    storeViewList,
    stopFetchProcess,
  }
}

这是要调度的 viewReducer.js:

const types = {
    START_LOADING: 'START_LOADING',
    STORE_VIEW_LIST: 'STORE_VIEW_LIST',
    STOP_LOADING: 'STOP_LOADING',
}

export const initialState = {
    isLoading: false,
    rows: [
      {
        ProfilePicture: 'Avatar',
        id: 'id', Name: 'Name', Price: 'Price', Discount: 'Discount'
      }
    ],
  }

  export const actions = {
    storeViewList: (data) => ({ type: types.STORE_VIEW_LIST, value: data }),
    startFetchProcess: (loading) => ({ type: types.START_LOADING, value: loading }),
    stopFetchProcess: (stopLoading) => ({ type: types.STOP_LOADING, value: stopLoading })
  }

  export const reducer = (state, action) => {
    switch (action.type) {

        case types.START_LOADING:
          const Loading = { ...state, ...action.value }
          return Loading

        case types.STORE_VIEW_LIST:
            const List = { ...state, ...action.value }
            return List

        case types.STOP_LOADING:
          const stopLoading = { ...state, ...action.value }
          return stopLoading

        default:
          return state;
      }
  }

  export const register = (globalState, globalActions) => {
    globalState.viewSystem = initialState;
    globalActions.viewSystem = actions;
  }

这是 StoreProvider 提供应用程序中的每个组件并传递状态:

import React, { useReducer } from "react"
import { reducer, initialState, actions } from '../reducers'

export const StoreContext = React.createContext()

export const StoreProvider = props => {
  const [state, dispatch] = useReducer(reducer, initialState)

  return (
    <StoreContext.Provider value={{ state, actions, dispatch }}>
      {props.children}
    </StoreContext.Provider>
  )
}

这是为不同视图克隆许多 reducer 的 reducers index.js:

import { user as userData, reducer as loginReducer } from './loginReducer'
import { register as viewRegister, reducer as viewReducer } from './viewReducer'
import { register as groupRegister, reducer as groupsReducer } from './groupsReducer'


export const initialState = {};
export const actions = {};

userData(initialState, actions)
viewRegister(initialState, actions)
groupRegister(initialState, actions)

export const reducer = (state, action) => {
  return {
    credentials: loginReducer(state.credentials, action),
    roleSystem: viewReducer(state.viewSystem, action),
    groups: groupsReducer(state.groups, action)
  }
}

很抱歉有很多文件,但没有其他方法可以解释这种情况。曾经使用过 Redux 的人可以理解这种方法。state => action => dispatch system 没有问题,直到我尝试使用页面的初始渲染获取数据(在这个例子中,我称之为 View)。

经典的let didCancel = false方法不起作用。如果我将状态与新获取的数据进行比较,问题就解决了。但是当我添加加载时,它会触发 useReducer 并重新渲染页面,这会导致无限循环。

UseRef 和 clearInterval 不会阻止它,并且会发生此错误:

Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

标签: reactjsreact-hooksuse-effect

解决方案


我会尝试分散您的关注以startFetchProcess在初始渲染上调度操作,然后在加载状态更新时获取:

useEffect(() => {
  viewContextRef.current.startFetchProcess()
}, [])



 useEffect(() => {
 // Fetch Data
  async function fetchData () {
    // This causes the loop
    // moved to the dependency array
    const url = 'http://example.com/fetch/data/'

  // ..... //

  function doStartFetch () {
    roleContext.state.isLoading && fetchData()
  }

  const startingFetch = setInterval(doStartFetch, 500)
  // aborting request when cleaning
  return () => {
    clearInterval(startingFetch)
  }
}, [roleContext.state.isLoading])

推荐阅读