【问题标题】:TypeError: this.setState is not a function with es6 functionTypeError: this.setState 不是带有 es6 函数的函数
【发布时间】:2019-10-25 23:24:26
【问题描述】:

我理解使用 bind.(this) 和 es6 fat 箭头函数(这是我正在使用的),但它仍然返回此错误消息,我不知道为什么。我的代码:

编辑:按要求添加了课程的其余部分。

export default class Result extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data:''
        }
    }



    testAxios(e) {

        e.preventDefault();

        axios.post('some api',
            {
                "Some-Data"
            })
            .then(response => {
                console.log('Returned Data:', response.data);
                this.setState({ data: response.data });
                console.log('State data:', this.state.data);
            })
            .catch(err => {
                console.log(err);
            })
    }


    render() {
        return ()
    }

【问题讨论】:

  • 错误信息是什么?
  • 我们能看到完整的课程吗?
  • 增加了全班。我得到了很好的数据响应,它的状态设置引发了上述类型错误。据我所知,我在 es6 函数中正确使用了它。
  • 你在哪里打电话testAxios?
  • 底部的return中只是一个按钮。

标签: reactjs ecmascript-6 axios


【解决方案1】:

testAxios(e) {} 未绑定。

你有两个选择:

  1. 在构造函数中将 this.testAxios 绑定到 this: this.testAxios = this.testAxios.bind(this);
  2. 使用箭头功能:testAxios = (evt) => { ... }

我建议您对类组件中的所有自定义方法使用箭头函数。

【讨论】:

    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2017-06-16
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多