【问题标题】:Cant Save Post Request Body Data无法保存发布请求正文数据
【发布时间】:2019-10-18 06:52:13
【问题描述】:

我在使用 Node.js 和 React.js 从 fetch post 请求中保存数据时遇到问题。我正在从 React 组件类中的函数调用 fetch 请求。我想从我的数据库中查询一些用户 ID,然后将其保存到 React 组件实例变量之一,即“this.userid”但是,每当我将值分配给一个空变量时,我都会在“.then”语句之外检查它你可以看到它从未被分配。

是否有人知道执行获取请求的方法或正确方法?我正在创建一个简单的登录发布请求,并希望在从 API 返回后保存用户 ID。

class LandingPage extends React.Component {
constructor(props) {
    super(props) 
    this.data = data
}   
login(e){
    var that = this;
    function log(id){
       that.userid = id
    }
    fetch("/login", {
        method: "POST",
        headers: {
            'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            },
        body: JSON.stringify(this.data)
    }).then(response => {
        return response.json();
    })
    .then(json =>log(json.userid))
   /both show undefined
   console.log(that.userid, this.userid)  
   }

【问题讨论】:

    标签: reactjs asynchronous fetch


    【解决方案1】:

    您正在检查 then 范围之外的数据。它在那里不存在,因此您必须在 .then() 中使用检索到的数据调用 setState。

    改变 .then(json =>log(json.userid))

    .then(json => {
      that.setState({userid: json.userid})
    })
    

    那么,在组件更新后,带有userid的状态可用

    更新:或者,您可以使用 async await 并像这样构建它:

    import React from 'react';
    
    class MyComponent extends React.Component {
    
      state = {
        userId: null
      }
    
      useFetch = async e => {
        const raw = await fetch("/login", {
          method: "POST",
          headers: {
            'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.data)
        });
    
        const json = await raw.json();
    
        this.setState({
          userId:json
        }, () => console.log(this.state))
      }
    
      render() {
        if (this.state.userId === null)
          this.useFetch();
        return (
          <div>Loading some data</div>
        )
      }
    }
    
    export default MyComponent;
    

    经过测试和工作的组件。

    【讨论】:

    • 我将 then 语句更改为 that.setState 但它也没有定义它:/
    • 你确定你用过var that = this;that.setState()吗?
    • @JLask 检查更新,我为你写了一个异步等待版本
    猜你喜欢
    • 2020-04-12
    • 2014-08-01
    • 2021-10-31
    • 2020-10-03
    • 1970-01-01
    • 2023-03-26
    • 2020-12-13
    • 1970-01-01
    相关资源
    最近更新 更多