[英]What's wrong with setInterval method?
I'm designing a screen in a mobile app that is supposed to disappear automatically and navigate to the next screen.我正在一个移动应用程序中设计一个屏幕,该屏幕应该自动消失并导航到下一个屏幕。 for that purpose I'm using setInterval in following code :
为此,我在以下代码中使用 setInterval :
componentDidMount(){
Animated.timing(this.state.AnimVal, {
toValue: 1,
duration: 500 ,
delay: 1000,
useNativeDriver: true,
}).start();
var timer = setInterval( () => {
this.setState({
isLoaded: true,
});
}, 1000);
if(this.state.isLoaded){
this.props.navigation.navigate({ routeName: 'Guideline'})
};
};
the isLoaded state variable method is supposed to become true and as a result of it, the screen must disappear. isLoaded 状态变量方法应该变为真,因此,屏幕必须消失。 but it does not happen and the screen remains.
但它不会发生并且屏幕仍然存在。 any idea what's wrong with it?
知道有什么问题吗?
this is because when the setInterval setState called, it will re-render the component, but they don not called componentDidMout.这是因为当 setInterval setState 调用时,它会重新渲染组件,但它们不会调用 componentDidMout。
for react-native > 0.6:对于本机 > 0.6:
static getDerivedStateFromProps(props, state){
if(state.isLoaded){
//here may be has problem
props.navigation.navigate({ routeName: 'Guideline'})
};
}
for react-native < 0.6:对于反应原生 < 0.6:
componentWillReceiveProps(nextprops){
if(this.state.isLoaded){
this.props.navigation.navigate({ routeName: 'Guideline'})
};
}
I suggest it use componentDidUpdate for your condition.我建议它根据您的情况使用 componentDidUpdate 。 because getDerivedStateFromProps is static.
因为 getDerivedStateFromProps 是静态的。 it can not call this.props.navigation
它不能调用 this.props.navigation
componentDidUpdate(prevProps, prevState, snapshot) {
if(this.state.isLoaded){
this.props.navigation.navigate({ routeName: 'Guideline'})
};
}
The problem is , you are calling the问题是,您正在调用
if(this.state.isLoaded){
this.props.navigation.navigate({ routeName: 'Guideline'})
};
inside the componentDIdMount, so its always false, and even though setState re-renders it and makes the state of isLoadedTrue, but it doesnt call the componentDidMount as per the lifecyle methods of react.SO that condition never gets called again.在 componentDIdMount 内部,因此它始终为 false,即使 setState 重新渲染它并使状态为 isLoadedTrue,但它不会按照 react.SO 的生命周期方法调用 componentDidMount,因此该条件永远不会再次被调用。
You can try to write that particular code inside componentDidUpdate() .您可以尝试在 componentDidUpdate() 中编写该特定代码。
componentDidUpdate(){
if(this.state.isLoaded){
this.props.navigation.navigate({ routeName: 'Guideline'})
};
}
And one more thing, rather than setInterval
try using setTimeout
, coz that will suffice in your case.还有一件事,而不是
setInterval
尝试使用setTimeout
,因为这在您的情况下就足够了。 and use the setTimeout inside the componentDidMount itself.并在 componentDidMount 本身内部使用 setTimeout。 That logic of yours is fine, just the navigation logic put it into
comopnentDidUpdate()
你的那个逻辑很好,只是导航逻辑把它放到了
comopnentDidUpdate()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.