繁体   English   中英

在获取POST时使用ReactJS,然后使用then函数设置setState

[英]ReactJS when Fetch POST, and use then function to setState

在我的ReactJS项目中,我使用fetch做异步处理,然后在获取数据之后,

我想setState更改我的本地状态。 但是我得到了错误返回。

Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined

获取功能代码:

AddDeal(deal){
fetch('shops/1/deals',{
      method: "POST",
      body: JSON.stringify(deal),
      headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
      },
    }).then(response => {
         response.json().then(data =>{
           this.setState({deals: data}); // and use this.props.dispatch I get `props` of undefined 
         })
      })
}

我看过另一个问题,例如我的React.js:使用Fetch API和对象数组中的props加载JSON数据

那么我该如何解决呢?

当调用fetch()价值this将是响应,而不是类。 您可以保存的值, this通过将其分配给一个变量,通常被称为self

AddDeal(deal){
  const self = this;
  fetch('shops/1/deals',{
    method: "POST",
    body: JSON.stringify(deal),
    headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
    },
  }).then(response => {
    response.json().then(data =>{
      self.setState({deals: data});
    })
  })
}

这可能会解决您的问题:

AddDeal = (deal) => {
  fetch('shops/1/deals',{
    method: "POST",
    body: JSON.stringify(deal),
    headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
    },
  }).then(response => {
    response.json().then(data =>{
      this.setState({deals: data});
    })
  })
}

这样尝试,这是正确的方法

constructor(props) {
    super(props)

   ..............
   ..............
   ..............

    this.AddDeal = this.AddDeal.bind(this)
}

我建议您使用Axios而不是fetch,因为与Fetch相比,axios具有更多强大的功能。 您可以从Link那里了解Axios的强大功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM