Reactjs TypeError:这是未定义的吗?
我无法达到此状态,或者我无法在Reactjs TypeError:这是未定义的吗?,reactjs,this,state,Reactjs,This,State,我无法达到此状态,或者我无法在componentDidMount函数中设置状态。为什么? import React from 'react'; class LoginApi extends React.Component { constructor(props) { super(props); this.state = { formNames: [], }; } componentDidMount(
componentDidMount
函数中设置状态。为什么?
import React from 'react';
class LoginApi extends React.Component {
constructor(props) {
super(props);
this.state = {
formNames: [],
};
}
componentDidMount() {
let apiKey = '###';
window.JF.initialize({ apiKey: apiKey });
window.JF.login(
function success() {
window.JF.getForms(function(response) {
for (var i in response) {
this.setState({ formNames: [...this.state.formNames, response[i]] });
}
});
},
function error() {
window.alert('Could not authorize user');
}
);
}
render() {
return (
<div className="initializeForm">
<ul>
{this.state.formNames.map(forms => (
<li key={forms}>{forms}</li>
))}
</ul>
</div>
);
}
}
export default LoginApi;
因为您编写的成功函数没有绑定/不是箭头函数。如果没有它,则表示调用函数。在这种情况下,将调用success函数。将其更改为箭头功能,它将工作。()=>{…},因为您正在另一个函数中引用此。当您在
JF.login
中创建回调函数,并再次在JF.getForms
中使用function关键字创建回调函数时,它会创建一个回调函数,因此setState
是未定义的
解决这一问题的一种常见方法是使用,它最终将从其封闭的词法范围中使用this
,在您的例子中,它就是类
window.JF.login(
() => {
window.JF.getForms((response) => {
for (var i in response) {
this.setState({ formNames: [...this.state.formNames, response[i]] });
}
});
},
() => {
window.alert('Could not authorize user');
}
);
您应该在设置状态之前对数组进行concat,因为setState是异步的,并且不会在for循环中返回更新的数组。只将最后一项添加到数组中。永远不要发布api密钥或其他凭据。遗憾的是,它仍然无法工作。我在下面的链接中得到的警告很抱歉,我建议您阅读您收到的错误并从中继续。也就是说,返回对象键,然后将其连接到状态数组中,然后尝试渲染状态数组,因此React抛出此错误的原因是什么。你是不是想用一句话来代替?
window.JF.login(
() => {
window.JF.getForms((response) => {
for (var i in response) {
this.setState({ formNames: [...this.state.formNames, response[i]] });
}
});
},
() => {
window.alert('Could not authorize user');
}
);