在我的react组件中,我试图在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调用了它),为什么我会收到此错误?我认为一旦安装了组件,就可以安全地设置状态了?
没有看到渲染功能有点困难。尽管已经可以发现应该执行的操作,但是每次使用间隔时,都必须在卸载时清除它。所以:
componentDidMount() { this.loadInterval = setInterval(this.loadSearches, this.props.pollInterval); } componentWillUnmount () { this.loadInterval && clearInterval(this.loadInterval); this.loadInterval = false; }
由于卸载后仍可能会调用这些成功和错误回调,因此可以使用interval变量检查其是否已安装。
this.loadInterval && this.setState({ loading: false });
希望这会有所帮助,如果这样做不起作用,请提供渲染功能。
干杯