【发布时间】:2019-06-23 18:10:14
【问题描述】:
我正在从构造函数调用方法中设置状态,但状态属性仍然为空。对代码的一些修改在控制台中给出了这个错误,
index.js:1375 警告:无法在尚未安装的组件上调用 setState。这是一个无操作,但它可能表明您的应用程序中存在错误。而是直接分配给this.state 或在ResultContainer 组件中定义具有所需状态的state = {}; 类属性。
在我的组件构造函数中,我正在调用一个方法。该方法又调用另一个方法并尝试使用数组填充状态属性。我得到两种不同的错误/警告变体。在我的代码中,如果取消注释渲染方法中的行,我会得到 searchedAddress 为空错误。如果我将这些行保留为注释,那么在控制台中我会收到上述错误。
在我的 render() 方法中,我可以检查 null 并且肯定不会抛出错误,但是无论我做什么,结果项都不会被加载。这个问题,State not changing after calling this.setState 似乎有些相关,但我不确定我是否可以异步重新渲染该项目。
import React from 'react';
import ResultItem from './ResultItem'
import AddressService from '../Api/AddressService'
class ResultContainer extends React.Component{
constructor(props){
super(props);
this.state = {
searchedAddresses : null
}
this.intiateSearch();
}
intiateSearch =() => {
if(this.props.searchedTerm != null){
var addressService = new AddressService();
//this is just getting an items from json for now. i checked and result does contain items
var result = addressService.searchAddress(this.props.searchedAddresses);
//the below line does not seem to work
this.setState({
searchedAddresses : result
});
}
}
render(){
return(
<div className="mt-3">
<h4>Seaching for postcode - <em className="text-primary">{this.props.searchedTerm}</em></h4>
<div className="container mt-1">
{
//below gives an error stating searchedAddresses is null
// this.state.searchedAddresses.map((address, index)=>{
// return(<ResultItem address={address}/>);
// })
}
</div>
</div>
);
}
}
export default ResultContainer;
【问题讨论】:
-
将
this.intiateSearch()移动到componentDidMount,使用异步/等待
标签: reactjs