【问题标题】:external function not accepting this.setState or this.state不接受 this.setState 或 this.state 的外部函数
【发布时间】:2019-03-04 20:03:03
【问题描述】:

我有一个名为 postdata.js 的函数组件文件,我在 app.js 中使用它。在 postdata 内部,我有一个从 API 获取值的函数(正在工作)。但是当我在调用的 postdata 函数中使用 this.setState 并将其分配给 API 结果值时,我会抛出一个错误:

Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined

postdata.js:

export function Postdata(url=''){

  return fetch(url).then(
     function(response){

         console.log("response.json()::",response)
         return response.json();
    })

}

app.js:

import React, { Component } from 'react';
import logo from './logo.svg';
import {Table} from 'reactstrap';
import './App.css';
import {Postdata} from './postdata';

class App extends React.Component {

  constructor(props){

    super(props);
      this.state = {
          hits: 'sduhyh',
          result_:[]
      }
 //this.Postdata = this.Postdata.bind(this)
    }

    componentDidMount() {}

  postdata_fire(){

    Postdata('http://localhost:3000/places').then(function(result){
      console.log("result::",result);
      this.setState({result:'sdujoij'})

})


    this.setState({hits:'yahittsss'})
    console.log("hits:::",this.state.hits); 
  }

  render() {
    return (
      <div className="App container">



   <div>{this.state.hits}</div>

        <button onClick={this.postdata_fire.bind(this)}></button>
      </div>
    );
  }
}

export default App;

请帮忙。

【问题讨论】:

标签: reactjs


【解决方案1】:

您需要像这样重构 postdata_fire:

postdata_fire() {
 Postdata('http://localhost:3000/places').then(result => {
   console.log("result:: %j",result);
   this.setState({result_: result});
 });
 ...
}

还有 Postdata:

export const Postdata = (url='') => {
  return fetch(url).then(response => {
    console.log("response.json()::",response)
    return response.json();
  });
}

【讨论】:

  • 我添加了您的代码,但没有效果。我也没有看到太大的不同
【解决方案2】:

您的承诺响应不共享 this 范围,因此请在 then 响应中使用箭头函数...


  postdata_fire(){
    Postdata('http://localhost:3000/places').then((result) =>{
      console.log("result::",result);
      this.setState({result:'sdujoij'})
    })

    this.setState({hits:'yahittsss'})
    console.log("hits:::",this.state.hits); 
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2018-11-13
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    相关资源
    最近更新 更多