[在React.js中获取API提取的数据后加载组件

问题描述 投票:0回答:3

我的组件代码如下

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
3个回答
1
投票

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

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

您也可以像rows && rows.length > 0一样写您的条件,与rows && rows.length相同。 rows.length如果为空,则将解析为0,即false,但如果大于0,则为true(类型转换或类型转换)。

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

2
投票

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

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

1
投票

尝试此componentWillUnmount() { this.props.countries = [] },可能会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.