2017-01-13 51 views
0

我正在使用scrollable tab view和facebook官方助焊剂解决方案。在有些情况下,当一个场景保持无效(不是当前选中的标签),并接收来自需要更新的场景商店的事件,但我有此错误: Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.组件已安装,但我无法调用this.setState(...)或this.forceUpdate(...);

我仔细检查过,并componentWillUnmount()是没有被调用..但我收到这个警告,我不能再更新组件的状态。

这里我有这个问题未被选择的选项卡是组件的一些示例代码:

constructor(props) { 
    super(props); 

    this.state = { 
     isFavorite: this.isCurrentPostFavorite, 
     isMounted: false, 
     value: 0, 
    }; 

    this.updateStateForFavoriteModification = this.updateStateForFavoriteModification.bind(this); 
    } 

    componentDidMount() { 
    this.setState({isMounted: true}); 
    console.log('Article Scene did mount for article: '.toUpperCase() + this.props.sceneInfo.article.name); 
    HotelStore.bind(HotelEvent.didModifiedFavorite, this.updateStateForFavoriteModification.bind(this)); 
    } 

    componentWillUnmount() { 
    this.setState({isMounted: false}); 
    console.log('Article Scene will unmount for article: '.toUpperCase() + this.props.sceneInfo.article.name); 
    HotelStore.unbind(HotelEvent.didModifiedFavorite, this.updateStateForFavoriteModification); 
    } 

    changeFavoriteStatus() { 
    if (this.state.isFavorite) { 
     sendAction(HotelAction.removeFavorite, this.props.sceneInfo.article); 
    } 
    else { 
     sendAction(HotelAction.addFavorite, this.props.sceneInfo.article); 
    } 
    } 

    updateStateForFavoriteModification() { 
    console.log('Update: '.toUpperCase() + this.props.sceneInfo.article.name); 
    console.log('isMounted: '.toUpperCase() + this.state.isMounted); 

    // 
    // 
    // Here I Get the error 
    this.setState({isFavorite: this.isCurrentPostFavorite}); 
    } 

    get isCurrentPostFavorite() { 
    let matchNumber = HotelStore.favoritesPosts.filter((el: Post) => { 
     return el.translationId === this.props.sceneInfo.article.translationId; 
    }).length; 
    let isFavorite = matchNumber > 0; 
    console.log(isFavorite); 
    return isFavorite; 
    } 

至于结果成分没有安装登录console.log('Article Scene will unmount for article: '.toUpperCase() + this.props.sceneInfo.article.name);更新状态之前从未显示,也this.setState(...)在布尔之前isMounted在日志中始终为true

编辑:我知道isMounted,这就是一个antipatern,我用这个只能在日志检查,如果组件被安装或没有,如果我删除isMounted逻辑错误仍然存​​在。

+0

请提供相关的代码示例 – mbernardeau

+0

@mbernardeau done –

+0

其中,所有'setState',在控制台中触发该错误/警告? – Chris

回答

0

首先,你不应该想检查你的组件是否安装,it's an antipattern

我想警告的出现是因为你在componentWillUnmount中使用了setState。我认为问题在于,setState是异步的,所以当您调用函数时,状态可能不会立即更改。在这种情况下,它可能会尝试更改组件已经卸载时的状态。

+1

我知道'isMounted',这是一个antipatern,我只用它来检查组件是否安装,如果我删除'isMounted'逻辑,错误仍然存​​在。 –

相关问题