2015-09-03 47 views
5

在我的组件我有以下几点:使用redux时如何在反应组件中取消订阅?

componentWillMount: function() { 
    this.unsubscribe = store.subscribe(function() { 
    this.setState({message: store.getState().authentication.message}); 
    }.bind(this)); 
}, 

componentWillUnmount: function() { 
    this.unsubscribe(); 
}, 

不调用取消导致以下错误:

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.

我想知道的是,我应该分配给unsubscribethis有一个更好的地方分配它?

+0

您应该尝试使用componentDidMount()而不是componentWillMount()。 – legolandbridge

+0

@legolandbridge,因为我仍然需要'取消订阅',所以没有任何区别。 – Clarkie

+0

您是否使用'react-redux'的'connect'和'Provider'进行了研究? –

回答

4

正如上述Salehen Rahman所述,我最终使用react-redux

按照他们的文档我创建了两个功能,一是在组件内映射“全局状态”的道具:

function mapStateToProps(state) { 
    return { 
    users: state.users.items 
    }; 
} 

和一个映射派遣行动传递到组件作为道具功能:

function mapDispatchToProps(dispatch) { 
    return { 
    lockUser: (id) => dispatch(actions.lockUser(id)), 
    unlockUser: (id) => dispatch(actions.unlockUser(id)), 
    updateUser: (id, user) => dispatch(actions.updateUser(id, user)), 
    addUser: (user) => dispatch(actions.addUser(user)) 
    }; 
} 

这则全部被拉到一起使用connect方法:

export default connect(mapStateToProps, mapDispatchToProps)(UsersContainer); 

我有一种感觉,所有这一切都在引擎盖上附加unsubscribe方法的组件,但它确实简化了很多事情。

+1

在引擎盖下,它的确将'unsubscribe'附加到'this'--但不是你的组件。 React Redux'connect()'产生一个中间组件:这就是为什么你接收数据为'this.props',而不是'this.state'。您应该在大多数情况下使用React Redux,而不是手动滚动它,因为它具有某些性能优化。 –