反应警告:无法从不同组件的函数体内部更新组件 [英] React Warning: Cannot update a component from inside the function body of a different component
问题描述
我在 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屋!