阵营本地的setState(...)既componentWillMount和componentDidMount
问题描述:
警告
我开始有反应过来母语,在我的项目,我到了一个地步,一切正常,但有这样的警告:阵营本地的setState(...)既componentWillMount和componentDidMount
Warning: setState(...): Can only update a mounted or mounting component.
所以,我看了几个QA,尝试了几个解决方案(从componentWillMount
和componentDidMount
更改setState()
的呼叫),但......警告总是在那里。
下面是代码的一部分:
REQUEST_URL = 'http://url/users.php';
(...)
module.exports = React.createClass({
getInitialState: function() {
return {
uid: null,
bid: null,
username: null,
}
},
componentDidMount: function() {
this.fetchData();
},
fetchData: function() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((json) => {
console.log('setState called');
this.setState({
uid: json.users[0].user_id,
bid: json.users[0].building_id,
username: json.users[0].username
});
})
.done();
},
render: function() {
if (!this.state.uid) { //user is not defined
console.log('not rendered');
return <Text>chargement...</Text>
}
// else
console.log('rendered');
var userId = this.state.uid;
var buildingId = this.state.bid;
var username = this.state.username;
return (
<View style={styles.content}>
<Text style={styles.label}>User Id</Text>
<Text>{userId}</Text>
<Text style={styles.label}>Building Id</Text>
<Text>{buildingId}</Text>
<Text style={styles.label}>Username</Text>
<Text>{username}</Text>
</View>
)
},
});
的users.php
返回一个JSON内容类型。
任何线索?
Thanx。
答
问题可能是在一次渲染中反复重新安装某些组件(认为这与初始值的表示有关,在此找不到问题),因此您的state
将被设置为未安装的组件。
如果您将state
设置为可在组件卸载时清除的解耦超时,则可以避免在未安装的组件上设置状态。
componentDidMount() {
this.mounted = true;
// this.fetchTimeout = setTimeout(()=>{
this.fetchData();
// });
},
componentWillUnmount() {
// clearTimeouts(this.fetchTimeout);
this.mounted = false;
},
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((json) => {
console.log('setState called');
if (this.mounted === true){
this.setState({
uid: json.users[0].user_id,
bid: json.users[0].building_id,
username: json.users[0].username
});
}
})
.done();
},
我仍然不知道我们是否应该使用TimerMixins
但这种方式没有这些工作。 (TimerMixins
采取清除所述组分的任何超时或间隔组保健)
编辑:更新样本仅呼叫仍安装在部件的setState
。 我不知道是否有更好的方法,但据我所知,直到现在,你不能取消提取请求。
是否有可能在网络调用返回之前卸载组件? –
这是一个在'immediateResetRouteStack()'中调用的路线,这可能是问题吗? – Bruno