我有以下代码:
class MainScreen extends Component {
constructor(props) {
super(props);
this.state = {
selectedTab: 'news'
};
}
componentWillMount() {
this.props.dispatch({
type:'isLoggedIn',
isLoggedIn: false
})
}
shouldComponentUpdate() {
console.log('shouldComponentUpdate: --------')
return false;
}
navigateToAuthScreen() {
this.props.navigator.immediatelyResetRouteStack([
rootRoutes.authScreen
]);
}
componentWillReceiveProps(nextProps) {
console.log('componentWillReceiveProps: ----');
if (!nextProps.isLoggedIn) this.navigateToAuthScreen();
}
render() {
console.log('rending: ----------------------');
return (
<View style={styles.container}>
<TabBarIOS tintColor={theme.accentColor} translucent>
<Icon.TabBarItem
iconName="newspaper-o"
title="News"
selected={this.state.selectedTab === 'news'}>
<SceneStack
initialRoute={newsRoutes.newsListing}
/>
</Icon.TabBarItem>
</TabBarIOS>
</View>
);
}
}
更新
我发现这个错误与TabBarIOS和Icon.TabBarItem有某种关系。
我已完全删除onPress={() => this.switchTabsOrPopStack('news')}
,但错误仍然存在。
我收到此错误:
警告:setState(...):只能更新已安装或安装的组件。这通常意味着您在已卸载的组件上调用了setState()。这是一个无操作。请检查TabBarItem组件的代码。
我不确定我错过了什么。
答案 0 :(得分:3)
这个有点模糊的错误有一个非常快速的解决方案,可以让你使用有问题的组件进行完整的堆栈跟踪。只需将以下代码放入控制台并尝试重新创建错误:
var warn = console.warn;
console.warn = function(warning) {
if (/(setState)/.test(warning)) {
throw new Error(warning);
}
warn.apply(console, arguments);
};
我有一种感觉,这个组件让你感到惊讶,我很确定问题不在于提供的代码,特别是因为你没有在提供的代码中设置状态。
答案 1 :(得分:1)
我在点击事件中使用内联函数时遇到了这个错误。
请尝试解压你的onPress-Handler:
onPress() {
this.setState({selectedTab: 'news'});
}
在你的onPress:
onPress={this.onPress.bind(this)}
答案 2 :(得分:1)
你可以尝试为'shouldComponentUpdate'返回true。
shouldComponentUpdate() {
console.log('shouldComponentUpdate: --------');
return true;}
答案 3 :(得分:1)
https://github.com/facebook/react/issues/3878上正在讨论的问题。
并显示导致此警告的组件名称......在以下链接中给出了解决方案
答案 4 :(得分:1)
它可能与您的navigateToAuthScreen()方法有关。
基本上,您在componentWillReceiveProps生命周期事件中更改场景,这会导致组件卸载。但React仍在进行生命周期事件并在某处调用setState。我不确定它是如何在引擎盖下运行的,但似乎在它完成前一个生命周期之前调用unmount直到render()。
使用Navigator时我有同样的警告,我在检查登录状态之前安装了主屏幕,如果我没有登录,我会换到登录屏幕。
我通过在应用启动时显示启动画面来修复它,确保在渲染屏幕之前初始化我的所有商店和登录状态等。