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

问题描述 投票:1回答:1

我想知道从rest api显示数据的最佳方法是什么。

其实我做的是:

  • componentDidMount()调用fetch函数;
  • setState存储我的回复
  • 如果设置了值,则在render()时检查三元组

它看起来像这样:

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>)}

我虽然从fetch调用我的constructor函数,但是在async中调用constructor函数很奇怪,你放弃了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调用显示数据的最佳方法是什么?

谢谢你的回答

reactjs api fetch call render
1个回答
1
投票

如果没有设置payload,你可以在null方法的早期返回render,而不是添加很多三元组。

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>;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.