我无法达到此状态或无法 setState
内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;
当我尝试使用此代码时,我收到
TypeError: this is undefined.
this.setState({formNames: [...this.state.formNames,response[i]]});
最佳答案
因为你在引用 this
在另一个函数中。当您在 JF.login
中创建回调函数时再次在 JF.getForms
与 功能关键字,它会创建一个 new this
context ,这就是为什么 setState
未定义。
解决此问题的常用方法是使用 arrow function ( =>
) ,这将最终使用 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');
}
);
关于reactjs - 类型错误 : this is undefined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57339517/