【问题标题】:Uncaught TypeError: Cannot read property 'fetch' of undefined未捕获的类型错误:无法读取未定义的属性“获取”
【发布时间】:2019-02-26 14:05:52
【问题描述】:

我正在做一个示例 ReactJS 应用程序,我正在尝试通过“RestAPI POST”发送表​​单数据。下面给出了代码 sn-ps,但是,它不起作用。

组件的 render() 如下所示。填写表格后,当用户单击“提交”按钮时,会调用“handleSubmit”。

render() {
    return(
    <button 
    label="Submit" 
    onClick={this.handleSubmit}>
    Submit
    </button>
}

'handleSubmit' 的定义如下所示,此处错误为 “Uncaught TypeError: Cannot read property 'fetch' of undefined”

handleSubmit() {

    this.fetch('https://example.domain.com/api/v1/task/actual', {
        method: 'POST',
        body: JSON.stringify({
            first_name: this.state.first_name,
            last_name: this.state.last_name
        })
        }).then(res => console.log('Success:', JSON.stringify(res)))
      .catch(error => console.error('Error:', error));
}

为了清楚起见,我也分享了 fetch 的定义。访问令牌很好。它适用于其他组件。

fetch(url, options) {
        const accessToken = 'Bearer ' + auth.getAccessToken();
        const headers = {
            'Content-Type': 'application/json',
            'Authorization' : accessToken
        }
        return fetch(url, {
            headers,
            ...options
        })
  }

我错过了一些东西,我无法弄清楚。请多多指教。

【问题讨论】:

标签: javascript reactjs rest


【解决方案1】:

fetch 未定义的原因是因为this 不是组件。如果您将 handleSubmit 函数定义更改为:

handleSubmit = () => {

那么你的代码应该可以工作了。请注意,这可能需要更改您的转译设置。或者,您可以在构造函数中绑定您的 handleSubmit 函数,使其具有正确的this

【讨论】:

    【解决方案2】:

    在您的构造函数中添加以下代码。

    this.handleSubmit = this.handleSubmit.bind(this);
    

    另一件事是确保在此实例中存在 fetch 函数。该 fetch 在您的组件类中声明,或者如果您从某个外部文件导入它,请在您的构造函数中添加以下行。

    this.fetch = fetch.bind(this);
    

    【讨论】:

      【解决方案3】:

      在 React 文档中解释得很好。继续阅读吧。
      https://reactjs.org/docs/handling-events.html

      【讨论】:

        猜你喜欢
        • 2021-12-22
        • 1970-01-01
        • 2021-12-25
        • 2017-07-26
        • 2015-01-06
        • 2021-11-24
        • 2021-10-31
        相关资源
        最近更新 更多