【问题标题】:Load a component after getting API fetched data in React.js在 React.js 中获取 API 获取的数据后加载组件
【发布时间】:2019-11-30 16:34:54
【问题描述】:

我的组件代码如下

componentDidMount = () => {
    this.props.dispatch(getCountry());
}


render() {

let rows = this.props.countries.map((item, index) => (//some code here));


return (
      <div>
        {rows ? (
          //components HTML code here
       ) : (
          <img src="loading.gif" alt="Loading ..."/>
        )}
      </div>
)
}

但组件在 API 获取数据之前加载。

【问题讨论】:

    标签: reactjs api mount


    【解决方案1】:

    rows 是一个数组,因此!rows 仍然为真。试试这个:

    return (
          <div>
            {rows && rows.length ? (
              //components HTML code here
           ) : (
              <img src="loading.gif" alt="Loading ..."/>
            )}
          </div>
    )
    

    【讨论】:

      【解决方案2】:

      您可以检查rows 数据,因为如果未获取,它将是一个空数组。

      return (
            <div>
              {rows && rows.length ? (
                //components HTML code here
             ) : (
                <img src="loading.gif" alt="Loading ..."/>
              )}
            </div>
      )
      

      你也可以像rows &amp;&amp; rows.length &gt; 0一样写你的条件rows &amp;&amp; rows.lengthrows.length 如果为空将解析为0,即false,但如果大于0 将解析为true(类型转换或类型转换)。

      return (
            <div>
              {(rows && rows.length > 0 ? (
                //components HTML code here
             ) : (
                <img src="loading.gif" alt="Loading ..."/>
              )}
            </div>
      )
      

      【讨论】:

        【解决方案3】:

        试试这个componentWillUnmount() { this.props.countries = [] },这可能对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-27
          • 2020-06-20
          • 2021-04-15
          • 2019-02-03
          • 2018-07-15
          • 2017-12-09
          • 1970-01-01
          • 2019-01-09
          相关资源
          最近更新 更多