【发布时间】:2019-07-06 12:42:49
【问题描述】:
我有这个组件:
// imports
export default class TabViewExample extends Component {
state = {
index: 0,
routes: [
{ key: 'first', title: 'Drop-Off', selected: true },
{ key: 'second', title: 'Pick up', selected: false },
],
};
handleIndexChange = index => this.setState({ index });
handleStateIndexChange = () => { // FUNCTION WITH THE ERROR
const { index } = this.state;
this.setState(({ routes }) => ({
routes: routes.map((route, idx) => ({
...route,
selected: idx === index,
})),
}));
};
renderTabBar = props => {
const { routes } = this.state;
this.handleStateIndexChange(); // HERE I GET THE ERROR
return (
<View style={tabViewStyles.tabBar}>
{props.navigationState.routes.map((route, i) => {
return (
<>
<TouchableOpacity
key={route.key}
style={[
tabViewStyles[`tabStyle_${i}`],
]}
onPress={() => this.setState({ index: i })}
>
<Text>
{route.title}
</Text>
// THE FUNCTION ATTEMPTS TO SHOW AN ELEMENT WHEN
// THE INDEX OF A ROUTE IS selected true
{routes[i].selected && (
<View
style={{
flex: 1,
}}
>
<View
style={{
transform: [{ rotateZ: '45deg' }],
}}
/>
</View>
)}
</TouchableOpacity>
</>
);
})}
</View>
);
};
renderScene = SceneMap({
first: this.props.FirstRoute,
second: this.props.SecondRoute,
});
render() {
return (
<TabView
navigationState={this.state}
renderScene={this.renderScene}
renderTabBar={this.renderTabBar}
onIndexChange={this.handleIndexChange}
/>
);
}
}
完全错误:
不变违规:不变违规:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。
这是给出错误的函数:
handleStateIndexChange = () => { // FUNCTION WITH THE ERROR
const { index } = this.state;
this.setState(({ routes }) => ({
routes: routes.map((route, idx) => ({
...route,
selected: idx === index,
})),
}));
};
我只需将selected 的状态设置为true,这样我就可以切换组件的可见性。
【问题讨论】:
-
您永远不会在此调用中直接在渲染中设置状态,方法是在渲染中调用执行该操作的函数。
-
@AdeelImran 我想给它打电话吗?
-
setStatein render 触发另一个render触发另一个setState在循环中。这是一种反模式。尝试在render之前将其提升为生命周期方法。 -
@KarenGrigoryan 如果你看到我的代码,我有这个
this.handleStateIndexChange(); // HERE I GET THE ERROR,这是我在renderTabBar内部调用的函数,它调用了渲染方法。另外,如果我在componentDidMount上使用setState,我会收到错误消息,即我不应该在componentDidMount函数上使用setState。 -
对不起,我的意思是
componentDidUpdate不是componentDidMount
标签: javascript reactjs ecmascript-6