我有一個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函數被調用(這可能是不錯的,更新越快越好)。解決這個問題的正確方法是什麼?
在此先感謝!