reactjs - 类型错误 : this is undefined?

标签 reactjs this state

我无法达到此状态或无法 setStatecomponentDidMount功能。为什么?

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/

相关文章:

javascript - React JS 和 Meteor JS 文件夹结构

Android:保存 XWalkView - 人行横道状态

javascript - 将 2 个函数转换为 1 个函数

django - 有没有办法阻止 django-pipeline 每次编译react.js代码时创建新的jsx文件?

c++ - 通过对象实例访问私有(private)静态成员

javascript - 为什么 JavaScript 的 bind() 在这里没有像我期望的那样工作?

javascript - JS 状态意外更新

javascript - 从 firebase 进行身份验证后,我想在状态中存储名称、电子邮件

javascript - npm install 无法解析依赖树

javascript - PHP 相当于 JavaScript "this"关键字,特别是在对象内?