在渲染期间做出反应、还原、调度操作



>我正在渲染不同的组件

render() {
switch(foo) {
case 'a': return <A/>
case 'b': return <B/>
default: return <C/>
}
}

现在我想跟踪每个屏幕的访问次数,并执行以下操作

render() {
switch(foo) {
case 'a':
this.props.dispatch(analytics.log({"screen": "A"}))
return <A/>
case 'b':
this.props.dispatch(analytics.log({"screen": "B"}))
return <B/>
default:
this.props.dispatch(analytics.log({"screen": "C"}))
return <C/>
}

我在渲染). Render methods should be a pure function of props and state.cannot update during an existing state transition (such as within收到错误

我无法将日志记录函数调用移动到componentDidMount,因为用户像tab一样移动这些屏幕。

在这种情况下,案例render是放置日志的理想位置,但反应建议我不要这样做。

我能做什么?

我假设您无法将此逻辑移动到componentDidMount因为它们都同时呈现(您提到了选项卡(,那么我会将其移动到切换选项卡的按钮的onClick处理程序。

将分派单移动到组件的componentDidMount<A /><B /><C />中。

我会将其包装到每个组件的onClick处理程序中。

例如:

onClick = ('A'/'B'/'C') => {
dispatch(analytics.log('A');
history.push('A') or switch tab to ('A') // however you are handling tab change.
} 

或者,您可以将调度移动到子组件中,以便在呈现它们时,将操作调度到子组件中。

在:

useEffect(() => { // or componentDidMount
dispatch(analytics.log('A')
}, []) 
// rest of A component.

最新更新