【发布时间】:2015-12-30 10:01:53
【问题描述】:
在我的反应组件中,我试图在 ajax 请求正在进行时实现一个简单的微调器 - 我使用状态来存储加载状态。
由于某种原因,我的 React 组件下面的这段代码抛出了这个错误
只能更新已安装或正在安装的组件。这通常意味着 您在未安装的组件上调用了 setState() 。这是一个无操作。 请检查未定义组件的代码。
如果我摆脱第一个 setState 调用,错误就会消失。
constructor(props) {
super(props);
this.loadSearches = this.loadSearches.bind(this);
this.state = {
loading: false
}
}
loadSearches() {
this.setState({
loading: true,
searches: []
});
console.log('Loading Searches..');
$.ajax({
url: this.props.source + '?projectId=' + this.props.projectId,
dataType: 'json',
crossDomain: true,
success: function(data) {
this.setState({
loading: false
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
this.setState({
loading: false
});
}.bind(this)
});
}
componentDidMount() {
setInterval(this.loadSearches, this.props.pollInterval);
}
render() {
let searches = this.state.searches || [];
return (<div>
<Table striped bordered condensed hover>
<thead>
<tr>
<th>Name</th>
<th>Submit Date</th>
<th>Dataset & Datatype</th>
<th>Results</th>
<th>Last Downloaded</th>
</tr>
</thead>
{
searches.map(function(search) {
let createdDate = moment(search.createdDate, 'X').format("YYYY-MM-DD");
let downloadedDate = moment(search.downloadedDate, 'X').format("YYYY-MM-DD");
let records = 0;
let status = search.status ? search.status.toLowerCase() : ''
return (
<tbody key={search.id}>
<tr>
<td>{search.name}</td>
<td>{createdDate}</td>
<td>{search.dataset}</td>
<td>{records}</td>
<td>{downloadedDate}</td>
</tr>
</tbody>
);
}
</Table >
</div>
);
}
问题是为什么我应该已经安装组件时出现此错误(因为它是从 componentDidMount 调用的)我认为安装组件后设置状态是安全的?
【问题讨论】:
-
在我的构造函数中我设置“this.loadSearches = this.loadSearches.bind(this);” - 生病添加到问题
-
您是否尝试在构造函数中将 loading 设置为 null?那可能行得通。
this.state = { loading : null }; -
嗨,我知道这是一个非常古老的帖子.. 但只是为了更新最新的发展:setstate 警告已从 React 代码库中删除(参见 PR)。原因是.. 1. 在某些情况下它们是误报 2. 避免误报会导致人们采用不受欢迎的代码模式,可读性较差 3. React 将“提供一个功能,让您保留 DOM 和状态,即使组件是不可见的”,而某些仅仅通过 setState 警告而采用的代码模式可能会导致将来出现不良行为。
标签: javascript ajax reactjs state