我有一个React Native组件,一旦它知道它是多大,它就会更新它的状态。 例子:React Native:在onLayout中更新状态给出了“警告:setState(...):无法在现有状态转换期间更新”
class MyComponent extends Component {
...
render() {
...
return (
<View onLayout={this.onLayout.bind(this)}>
<Image source={this.state.imageSource} />
</View>
);
}
onLayout(event) {
...
this.setState({
imageSource: newImageSource
});
}
...
}
这提供了以下错误:
Warning: setState(...): Cannot update during an existing state transition (such as within
render
or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved tocomponentWillMount
.
我猜,同时仍呈现onLayout函数被调用(这可能是不错的,更新越快越好)。解决这个问题的正确方法是什么?
在此先感谢!