【问题标题】:Best way to display data form an api call从 api 调用显示数据的最佳方式
【发布时间】:2019-08-02 01:12:59
【问题描述】:

我想知道从 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>)}

我虽然想从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 调用的数据的最佳方式是什么?

感谢您的回答

【问题讨论】:

  • 如果数据没有准备好就使用 if else 然后显示加载 else 输入。

标签: reactjs api fetch call render


【解决方案1】:

您可以在 null 尚未设置的情况下提前从 render 方法中返回 null,而不是添加许多三元组来检查是否设置了 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>;
  }
}

【讨论】:

  • 好的,谢谢,我做到了,它在重新渲染之前显示了一点“正在加载...”
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 2016-12-02
相关资源
最近更新 更多