reactJs警告:的setState(...):只能更新一安装或安装组件

问题描述:

我有以下代码:reactJs警告:的setState(...):只能更新一安装或安装组件

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组件的代码。

我不知道我错过了什么。

它可能与你的navigateToAuthScreen()方法来做给出的组件名称。

基本上,你在componentWillReceiveProps生命周期事件,这将导致组件卸载改变场景。但React仍然在经历生命周期事件,并在某处称为setState。我不确定它是如何工作的,但它似乎在它完成之前的生命周期直到render()之前调用卸载。

我使用导航仪时有同样的警告,我安装了主屏幕之前我检查登录状态,如果我没有登录,我会换一个登录界面。

我通过在应用程序启动时显示启动屏幕来确定它,确保在渲染屏幕之前初始化我的所有商店和登录状态等。

+0

因为导航器,我陷入了相同的情况,你可以详细说明如何解决这个问题。 –

我一直在使用内联函数时单击事件像你这样遇到此错误。

请尝试提取您的onPress处理程序:

onPress() { 
    this.setState({selectedTab: 'news'}); 
} 

而在你的onPress:

onPress={this.onPress.bind(this)} 
+0

我已经删除onPress完全和我仍然得到相同的错误.. –

你可以尝试返回了 'shouldComponentUpdate' 真。

shouldComponentUpdate() { 
console.log('shouldComponentUpdate: --------'); 
return true;} 

有一个非常快速解决这个有点模糊的错误,这将给你有违规成分完整的堆栈跟踪。只要把下面的代码到您的控制台,并试图重现错误:

var warn = console.warn; 
    console.warn = function(warning) { 
    if (/(setState)/.test(warning)) { 
     throw new Error(warning); 
    } 
    warn.apply(console, arguments); 
    }; 

我有一种感觉分量呈现问题与惊喜你,我相当肯定,问题不在于所提供的代码,尤其是因为你没有在提供的代码中设置状态。

+0

尝试没有工作 –

+0

@NetaMeta它没有提供一个更长的堆栈跟踪控制台? –

+0

它已经提供它,并没有帮助 –

问题上正在讨论https://github.com/facebook/react/issues/3878

,并显示其造成这个警告...的解决方案在以下链接

https://github.com/facebook/react/pull/3913