反应警告:无法从其他组件的函数体内更新组件 [英] React Warning: Cannot update a component from inside the function body of a different component

查看:94
本文介绍了反应警告:无法从其他组件的函数体内更新组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React中将Redux与类组件一起使用.在Redux存储中具有以下两个状态.

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

{ spinner: false, refresh: false }

在父组件"中,我有一个调度功能来更改此状态.

In Parent Components, I have a dispatch function to change this states.

class App extends React.Component {
  reloadHandler = () => {
    console.log("[App] reloadComponent");

    this.props.onShowSpinner();
    this.props.onRefresh();
  };

  render() {
    return <Child reloadApp={this.reloadHandler} />;
  }
}

在子组件中,我正在尝试重新加载父组件,如下所示.

In Child Component, I am trying to reload the parent component like below.

class Child extends React.Component {
  static getDerivedStateFromProps(props, state) {
    if (somecondition) {
      // doing some redux store update
      props.reloadApp();
    }
  }

  render() {
    return <button />;
  }
}

我收到如下错误消息.

警告:无法从组件的功能主体内部更新组件不同的组件.

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

如何删除此警告?我在这里做错了什么?

How to remove this warning? What I am doing wrong here?

推荐答案

对我来说,我正在React Hook中调度到我的redux存储.我必须派一个 useEffect 来与React渲染周期正确同步:

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 }
}

这篇关于反应警告:无法从其他组件的函数体内更新组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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