首页 > 解决方案 > 在 React.js 中获取 API 获取的数据后加载组件

问题描述

我的组件代码如下

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 获取数据之前加载。

标签: reactjsapimount

解决方案


rows是一个数组,因此!rows仍然是正确的。试试这个 :

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

推荐阅读