gpt4 book ai didi

javascript - undefined 不是对象 react-native

转载 作者:行者123 更新时间:2023-11-29 20:44:22 33 4
gpt4 key购买 nike

我在为获取 API 响应的数据设置状态时遇到问题

render() {
function getCode(text) {
fetch('url', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"telephone": text,
"password": "123123"
})
}).then(response => response.json())
.then(response => {
console.log(this.state.text)
console.log(this.state.uid)

this.setState({uid : response["data"]["telephone"]})
console.log(this.state.uid)
// this.setState({uid: response["data"]["telephone"]})
// console.log(this.state.uid);
})
}

这是我的构造函数

constructor(props) {
super(props);
this.state = {
text: '',
uid: ''
}
}

所以我只是发送一个请求,需要在状态中保存响应,但是我收到了一个错误:

TypeError: undefined is not an object (evaluating '_this2.state.text')]

注释的代码行是我尝试修复它的尝试。

更新 1:这是来自 API 的响应

{"data":{"telephone":["Some data"]}}

最佳答案

当组件在渲染函数中挂载时声明该函数

 class Something extends React.Component {
constructor(props) {
super(props);
this.state = {
text: '',
uid: ''
}
}

getCode = (text) => {
fetch('url', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"telephone": text,
"password": "123123"
})
}).then(response => response.json())
.then(response => {
console.log(this.state.text)
console.log(this.state.uid)

this.setState({uid : response.data.telephone})
console.log(this.state.uid)
// this.setState({uid: response["data"]["telephone"]})
// console.log(this.state.uid);
})
}

render() {
return(
//...you can call it this.getCode(/..../)
)
}

}

关于javascript - undefined 不是对象 react-native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54845134/

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