从 api 调用中显示数据的最佳方式

Best way to display data form an api call

我想知道显示休息数据的最佳方式是什么 api。

其实我是做什么的:

看起来像这样:

getcall()是一个获取函数):

async componentDidMount() {
    const response= await getCall(
        `event?ref=23876186`, // this is just to illustrate
      );
    this.setState({ payload: response})
}

然后在render()我做了一些:

 {this.state.payload ? (
  <h1>{this.state.payload.event.name}</h1>) : ( <h1></h1>)}

我想从 constructor 调用我的 fetch 函数,但是在 constructor 中调用 async 函数很奇怪,你失去了 aync 目的。

我想像 input 这样的情况:

  <Input 
     type="text" 
     name="name" 
     id="name" 
     **value={this.state.event.name}**
     placeholder="Name..." 
     onChange={this.handleName}
     required
   />

如果我想为它设置一个值,比如this.state.event.name,如果我有 10 个字段,我将有 10*2 次这种代码,因为我为每个字段写了一个三元。

那么显示 api 调用数据的最佳方式是什么?

感谢您的回答

与其在检查 payload 是否设置的地方添加大量三元组,不如在 render 方法未设置时尽早 return null还.

例子

class App extends React.Component {
  state = {
    payload: null
  };

  async componentDidMount() {
    const response = await getCall("/event?ref=23876186");
    this.setState({ payload: response });
  }

  render() {
    const { payload } = this.state;

    if (payload === null) {
      return null;
    }
    return <div>{/* ... */}</div>;
  }
}