[英]react native call setState within componentDidUpdate error
I've a multiscreen app using react-navigation and passing a prop from CameraScreen to HomeScreen called 'barcode' like so:我有一个使用 react-navigation 的多屏应用程序,并将一个名为“条形码”的道具从 CameraScreen 传递到 HomeScreen,如下所示:
takePicture() {
//Redirect
this.props.navigation.navigate('Home', {barcode: true});
}
Source: https://reactnavigation.org/docs/en/params.html资料来源: https://reactnavigation.org/docs/en/params.html
On home screen I'm listening for the prop update within componentDidMount and if barcode is true, setState to render a new component like so:在主屏幕上,我正在监听 componentDidMount 中的道具更新,如果条形码为真,则 setState 呈现一个新组件,如下所示:
componentDidUpdate(){
if(this.props.navigation.getParam('barcode') === true) {
this.setState({
barcodeActive: true
})
}
}
I get the error Invariant Violation: Maximum update depth exceeded
- from calling setState within componentDidMount.我收到错误
Invariant Violation: Maximum update depth exceeded
- 从 componentDidMount 中调用 setState。 I understand it's in an infinite loop with no break.我知道它处于无限循环中,没有中断。
How can I listen for when this prop is passed to setState or is there a better way to achieve what I'm after?当这个道具传递给 setState 或者有更好的方法来实现我所追求的目标时,我该如何监听?
You can use prevProps
argument, and then compare current and previous values of barcode
.您可以使用
prevProps
参数,然后比较barcode
的当前值和以前的值。 If they are not the same, then you can update your state.如果它们不一样,那么您可以更新您的 state。
componentDidUpdate(prevProps){
if(this.props.navigation.getParam('barcode') !== prevProps.navigation.getParam('barcode')) {
if( this.props.navigation.getParam('barcode')) {
this.setState({
barcodeActive: true
})
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.