React js 状态对象在渲染方法中无法识别
2020-09-07
618
我是 React 的新手,在 componentDidMount 中,我从 Axios 检索响应对象,然后将其设置为状态对象,即使它可以从外部函数访问,但它在 render 方法内部不起作用,我不知道如何绑定状态以访问 render()
弹出的错误:未处理的拒绝(TypeError):无法读取未定义的属性“imageref”
export default class Product extends Component {
constructor(props) {
super(props);
const id = this.state.comicId;
console.log("This is printed from the constructor " + id);
}
state = {
comicId: "",
issueObjectState: "",
};
render(){
<img
src={this.state.issueObjectState.imageref}
alt="Image Description"
className="mx-auto img-fluid"/>
}
async componentDidMount() {
let state = [];
const id = this.props.location;
let comicId = id.data;
this.setState({ comicId: this.props.comicId });
let issueData = await axios.get(`http://localhost:5000/comic/${comicId}`);
let comicData = issueData.data;
if (comicData) {
this.setState({ issueObjectState: comicData });
console.log(this.state.issueObjectState);
}
}
}
非常感谢您的帮助
3个回答
我发现您的代码中有很多错误,首先是在构造函数方法之外声明状态,因此您应该首先执行以下操作:
constructor(props) {
super(props);
this.state = {
comicId: "",
issueObjectState: "",
};
}
然后生命周期方法不能与它之前的 async 关键字一起使用,您的异步函数必须在生命周期方法内。
Adel A
2020-09-07
我认为您必须将
this.state
对象转移到构造函数。
export default class Product extends Component {
constructor(props) {
super(props);
state = {
comicId: "",
issueObjectState: "",
};
const id = this.state.comicId;
console.log("This is printed from the constructor " + id);
}
}
Mehdi Rajani
2020-09-07
您正在尝试访问对象
this.state.issueObjectState.Imageref
在将对象分配给
espectionBoctState
之前。在发生错误时,
esseabjectState
简单地
“”
isseabjectState
。但是,最好是避免componentwillmount alltolterther,也许在您的情况下,只需分配一个null值
Tobi
2020-09-07