即使提取成功,方法返回未定义?

Method returning undefined even though fetch succeeds?

我有两个组件,Client 和 App,以及一个 fetch 函数。 App是Client的子组件。我想使用 App 调用方法中的 return 值更新客户端的状态。但是,客户端的状态响应在获取之后是未定义的。我不确定为什么这段代码不起作用。

import React, { Component } from 'react';
import './App.css';  

function post(user, token, data){
  console.log('fetching...')
  fetch(`/project`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Basic '+ btoa(user+':'+token),
    },
    body: JSON.stringify(data)
  }).then(r => {
      if (!r.ok)
        throw Error(r.status);
      r.json().then(r => {return(r)});
  }).catch(error => {throw Error(error)})
}

class Client extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: '',
      token: '111',
      project: {'project':'demo'},
      response: {},
    };

    this.updateState = this.updateState.bind(this);
  };


  updateState(){
    const { user, token, project } = this.state;
    post(user, token, project).then(text => this.setState({ response: text 
  }));
  }

  render() {
    return (
        <App updateState={this.updateState}/>
    )
  }
}

class App extends Component {      
  render() {
    return (
      <div className="App">
          <button onClick={ () => {
             this.props.updateState()} }>Fetch Project</button>
      </div>
    );
  }
}

编辑:我将我的 post() 更改为这个并且它有效:)

async function post(user, token, data){
  console.log('fetching...')
  const response = await fetch(`/project`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Basic '+ btoa(user+':'+token),
    },
    body: JSON.stringify(data)
  }).catch(error => {throw Error(error)});

  if(!response.ok)
    throw Error(response.status);
  
  const obj = await response.json();
  return(obj);
}

如果知道 fetch 函数的所有代码就好了,但我认为问题主要出在这里:

this.props.updateState(post())

该调用是同步的,而获取过程不是。您需要一种更好的方法,使用 await 或 promises 或回调。

如果你正在使用 promises,你可以这样做。

import React, { Component } from "react";
    async function post() {
      // fetch //
      return await fetch("https://hipsum.co/api/?type=hipster-centric");
    }

    class Client extends Component {
      constructor(props) {
        super(props);
        this.state = {
          response: "12"
        };
        this.updateState = this.updateState.bind(this);
      }

      async updateState(res) {
        const text = await res().then(res => res.text());
        this.setState({ response: text });
      }

      render() {
        return (
          <>
            {this.state.response}
            <App updateState={this.updateState} />
          </>
        );
      }
    }

    class App extends Component {
      render() {
        return (
          <div>
            <button
              onClick={() => {
                this.props.updateState(post);
              }}
            >
              Fetch
            </button>
          </div>
        );
      }
    }

    export default Client;

sandbox