首页 > 解决方案 > 如何使用两个返回语句在 React 组件中设置三元运算符“加载”Div?

问题描述

我使用的 API 很慢。我的 React 组件使用 FetchAPI 并且有两个返回语句。

我想合并一个三元运算符条件,在等待这样的数据时显示“正在加载..” div :https ://codesandbox.io/s/api-fetch-using-usestate-useeffect-k024k

如何在下面的代码中包含带有两个返回语句的“加载”三元组?注意:我大大减少了我的代码,以免让任何人发疯,所以我只包括了整体结构。别客气!

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }

  componentDidMount() {
    fetch('https.data.json')
      .then(response => response.json())
      .then(data => this.setState({ data: data}))
  }

  render() {

    let theList = this.state.map((item, id) => {

      return (
        <Card>A bunch of API Stuff </Card>
      );

    })
    return (
      <div className="search-wrap">
        <Row>
          {theList}
        </Row>
      </div>
    )
  }
}

export default App;

标签: javascriptreactjsfetch-api

解决方案


只需在您的状态中添加一个布尔字段,表明正在加载数据。

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: true, // this one
    };
  }

  componentDidMount() {
    fetch('https.data.json')
      .then(response => response.json())
      .then(data => this.setState({ data: data, loading: false }))
  }

  render() {

    if (this.state.loading)
       return <div>Loading...</div>

    let theList = this.state.map((item, id) => {

      return (
        <Card>A bunch of API Stuff </Card>
      );

    })
    return (
      <div className="search-wrap">
        <Row>
          {theList}
        </Row>
      </div>
    )
  }
}

export default App;

推荐阅读