[英]undefined is not an object react-native
我在为来自 fetch 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: ''
}
}
所以我只是发送一个请求,需要在状态内保存响应,但相反,我收到了一个错误:
类型错误:未定义不是对象(评估'_this2.state.text')]
注释的代码行是我试图修复它的尝试。
UPD 1:这是来自 APi 的回应
{"data":{"telephone":["Some data"]}}
问题是,你的方法中创建一个函数, this
函数中不参照this
在你的方法。
render() {
function getCode(text) {
// `this` in here is not the React component
}
}
这是一个简单的例子:
class Example { method() { // `this` within a method (invoked via `.`) points to the class instance console.log(`method=${this}`); function functionInAMethod() { // because functionInAMethod is just a regular function and // the body of an ES6 class is in strict-mode by default // `this` will be undefined console.log(`functionInAMethod=${this}`); } functionInAMethod(); } } new Example().method();
您可以将getCode
作为另一个类方法提取,并在需要时调用this.getCode()
。
getCode() {
// ...
}
render() {
this.getCode();
}
其他选择是:
bind
getCode
的this
call
或 [ apply][3]
设置this
getCode
的箭头函数来保留跨嵌套函数的this
this
绑定到render
中的变量并在getCode
使用该变量而不是this
⚠ 注意:您不想在render
方法中发出 http 请求,因为它被频繁调用,请考虑以不那么脆弱的方式进行。 通常的模式是在构造函数或componentDidMount
。
当组件确实安装在渲染函数中时,您声明该函数
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(/..../)
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.