gpt4 book ai didi

javascript - Reactjs:setState总是失败并在componentDidMount中返回undefined

转载 作者:行者123 更新时间:2023-12-03 23:30:46 25 4
gpt4 key购买 nike

在使用 setState() 时出现奇怪的错误,我总是没有设置状态:

错误代码:

TypeError: 无法读取 undefined(...) 的属性“setState”

class HelloWorld extends React.Component {
constructor() {
super();
this.state = {listings:[]};
};

componentDidMount (){
fetch('./javascripts/data.json').then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json ', json.listings);
this.setState({listings: 'test string'});
}).catch((error) => {
console.log(error);
})
}
render () {
return (
<ListingUser userData={this.state.listings} />
);
}
}

ReactDOM.render(
<HelloWorld />,
document.getElementById('example')
);

最佳答案

您收到此错误的原因是 this 没有在 promise 中引用您的组件类。为了使用this.setState(),你需要bind this 的正确上下文。

fetch('./javascripts/data.json')
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log('parsed json ', json.listings);
this.setState({listings: 'test string'});
}.bind(this))
.catch((error) => {
console.log(error);
});

您还可以使用箭头函数,它会在词法上绑定(bind) this 的正确值。

fetch('./javascripts/data.json')
.then(response => {
return response.json();
})
.then(json => {
console.log('parsed json ', json.listings);
this.setState({listings: 'test string'});
})
.catch(error => {
console.log(error);
});

关于javascript - Reactjs:setState总是失败并在componentDidMount中返回undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38003578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com