阵营警告:的setState(...)只能更新安装或安装组件
问题描述:
我有一个问题:我建立我的第一个应用程序与之反应/ ReactNative +流动,我得到这样的警告:阵营警告:的setState(...)只能更新安装或安装组件
setState(...):只能更新已安装或已安装的组件。这个 通常意味着你在卸载的组件上调用了setState()。这是一个无操作的 。请检查未定义组件的代码。
我上面的代码:
正如你可以看到我展示你在非常简单的方式的电影列表。现在显示一个改变视图的片段。我的问题来了,当我改变我的应用程序中的页面从显示电影的页面变为显示信息时发生变化。
class TabsView extends React.Component {
//do stuff...
renderContent() {
switch (this.state.tab) {
case 'List Movies':
return <ListMoviesView/>;
case 'Info':
return <InfoView/>;
}
}
render() {
return (
<View style={styles.content} key={this.state.tab}>
{this.renderContent()}
</View>
);
}
}
module.exports = TabsView;
我把一个日志()在第一个片段(因为这个问题住在这里),当功能_onChange()当我改变函数被调用几次页面,并获得了上述警告。如何解决它?我在哪里做错了?谢谢!
答
你到每个提供新功能比如你添加和删除事件侦听器的功能。因此,删除不会像预期的那样工作,因为它将目标设定为不同的功能实例,并且更改事件仍然会触发事件。
我猜你正在向匿名函数传递给添加/删除事件侦听器,以保持您的范围为this.setState
调用。您可以通过使用绑定到类属性的匿名函数维护范围,然后简单地引用您添加属性/删除通话,就像这样:
componentDidMount() {
ApiListMovies.getMovies();
ListMoviesStore.addChangeListener(this._onChange);
};
componentWillUnmount() {
ListMoviesStore.removeChangeListener(this._onChange);
};
// We use anonymous function bound to the class property, this
// will maintain our scope.
_onChange =() => {
console.log(this.state);
this.setState({
dataSource: this.state.dataSource.cloneWithRows(ListMoviesStore.getListMovies()),
loaded: true
});
};
注:以上依靠class properties syntax这是在建议和现在通过babel阶段1启用。如果你没有这个,你可以在构造函数调用中创建函数。像这样:
class ListMovies extends React.Component {
constructor(props) {
this.state = {
dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
loaded: false
};
// We use anonymous function bound to the class property, this
// will maintain our scope.
this._onChange =() => {
console.log(this.state);
this.setState({
dataSource: this.state.dataSource.cloneWithRows(ListMoviesStore.getListMovies()),
loaded: true
});
};
}
componentDidMount() {
ApiListMovies.getMovies();
ListMoviesStore.addChangeListener(this._onChange);
};
componentWillUnmount() {
ListMoviesStore.removeChangeListener(this._onChange);
};
好像你没有删除监听器。所以即使你改变了页面,_onChange函数也会触发。我对流量不熟悉,但是,听众能听到没有迹象吗? –