React Warning: Cannot update a component from inside the function body of a different component

前端 未结 10 1119
攒了一身酷
攒了一身酷 2021-01-01 12:24

I am using Redux with Class Components in React. Having the below two states in Redux store.

{ spinner: false, refresh: false }

In Parent C

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 12:44

    For me I was dispatching to my redux store in a React Hook. I had to dispatch in a useEffect to properly sync with the React render cycle:

    export const useOrderbookSubscription = marketId => {
      const { data, error, loading } = useSubscription(ORDERBOOK_SUBSCRIPTION, {
        variables: {
          marketId,
        },
      })
    
      const formattedData = useMemo(() => {
        // DISPATCHING HERE CAUSED THE WARNING
      }, [data])
    
      // DISPATCHING HERE CAUSED THE WARNING TOO
    
      // Note: Dispatching to the store has to be done in a useEffect so that React
      // can sync the update with the render cycle otherwise it causes the message:
      // `Warning: Cannot update a component from inside the function body of a different component.`
      useEffect(() => {
        orderbookStore.dispatch(setOrderbookData(formattedData))
      }, [formattedData])
    
      return { data: formattedData, error, loading }
    }
    

提交回复
热议问题