gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'info' of undefined

转载 作者:行者123 更新时间:2023-11-30 15:10:06 25 4
gpt4 key购买 nike

我对 react 还很陌生,在将数据从一种方法传递到另一种方法时遇到了问题。这是我的 react 语法:

var url = "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1"
class App extends React.Component{
info(val){
console.log(val)
}

request(){
axios.get(url)
.then(function (response) {
this.info(response)
console.log(response.data);
})
}

render() {
return(

<div>
<h1>axios</h1>
{this.request()}
</div>

)
}
}

ReactDOM.render(<App />, document.getElementById("target"))

我的目标是将响应数据从request 方法传递给info 方法。但是,我收到错误消息说 "TypeError: Cannot read property 'info' of undefined"你能帮我找出我遗漏了什么吗?

最佳答案

非常常见的问题,同样的问题有很多答案,因此将答案添加为社区 wiki。

这是一个绑定(bind)问题,你需要用回调绑定(bind)this

使用arrow function :

.then( (response) => {

有关详细信息,请查看此答案:Why is JavaScript bind() necessary?

关于javascript - 类型错误 : Cannot read property 'info' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228862/

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