react-native - setInterval 方法有什么问题?
问题描述
我正在设计一个移动应用程序中的屏幕,它应该会自动消失并导航到下一个屏幕。为此,我在以下代码中使用 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'})
};
};
isLoaded 状态变量方法应该变为真,因此,屏幕必须消失。但它没有发生,屏幕仍然存在。知道有什么问题吗?
解决方案
这是因为当 setInterval 调用 setState 时,它会重新渲染组件,但它们并没有调用 componentDidMout。
对于本机反应> 0.6:
static getDerivedStateFromProps(props, state){
if(state.isLoaded){
//here may be has problem
props.navigation.navigate({ routeName: 'Guideline'})
};
}
对于 react-native < 0.6:
componentWillReceiveProps(nextprops){
if(this.state.isLoaded){
this.props.navigation.navigate({ routeName: 'Guideline'})
};
}
我建议它根据您的情况使用 componentDidUpdate。因为 getDerivedStateFromProps 是静态的。它不能调用 this.props.navigation
componentDidUpdate(prevProps, prevState, snapshot) {
if(this.state.isLoaded){
this.props.navigation.navigate({ routeName: 'Guideline'})
};
}
推荐阅读
- javascript - JavaScript:点击链接没有切换
- kubernetes-ingress - Kubernetes Ingress Nginx 无法解析非根路径
- ios - 将 pixelBuffer(kCVPixelFormatType_420YpCbCr8Planar) 转换为 CIImage
- c++ - 如何在项目中添加和编译 mongoc 源代码并在本地使用(CMakeList 配置)
- apiconnect-test-monitor - 桌面应用程序代理设置
- java - Intellij IDEA:在 Java 项目中找不到要访问的声明
- c# - 如何使用 stringbuilder 将内容添加到 Asp.Net 中的 UpdatePanel
- python - 给定一个数组打印最不频繁的元素
- cookies - OpenAPI 安全方案:Cookie 身份验证中使用的“类型”是什么?
- java - 我的 webview 视频可以在模拟器上运行,但不能在设备上运行