【问题标题】:How to delay map within a component until ajax call is complete如何延迟组件内的映射直到 ajax 调用完成
【发布时间】:2018-04-23 13:06:05
【问题描述】:

我的应用程序中有一个 ajax 调用,如下所示:

  componentWillMount() {
    fetch('http://localhost:8081/',{method: 'GET', mode: 'cors'})
    .then(
      (results) => results.json()
      )
    .then(
      data => this.setState(data)
      )
    .then(
      () => console.log(this.state)
      )
    .catch(
      err => console.log(err))
  }

console.log 打印两次;一次处于“未定义”状态,然后在完成 ajax 调用时再次出现。问题是使用来自 ajax 调用的数据的组件;

componentDidMount(){
        const allProducts = this.props.products.map((val, ind) => 
            <div className="Product"><Product {...val} handleClick={this.props.handleClick} key={ind}/></div>
        );
      } 

...在数据返回之前进行映射,所以我遇到了错误:

Uncaught TypeError: Cannot read property 'map' of undefined

对不起,如果这对于本论坛来说太基本了。这可能是我忘记的直截了当的事情!

【问题讨论】:

  • 您正在设置状态中的数据,但是在渲染时,您正在使用道具。很抱歉,但我无法连接这些点。这里缺少一些东西。你能提供一个 git repo 或一个代码沙盒吗?这对我们来说会更容易。

标签: ajax reactjs components fetch lifecycle


【解决方案1】:

我认为在 render 中呈现 ajax 数据的最佳方式。 将构造函数中的状态设置为 null,这不会给您带来问题 未捕获的类型错误:无法读取未定义的属性“地图”。
类 SomeClass 扩展 React.Component {

    constructor(props) {
        super(props);
        this.state = { products: null };
    }
    componentWillMount() {
        fetch('http://localhost:8081/', { method: 'GET', mode: 'cors' })
            .then(
            (results) => results.json()
            )
            .then(
            data => this.setState(data)
            )
            .then(
            () => console.log(this.state)
            )
            .catch(
            err => console.log(err))
    }         



    render() {

        if (this.state.products == null) {
            return null;
        }
        return (<span>{
            this.state.products.map((val, ind) =>
                <div className="Product"><Product {...val} handleClick={this.props.handleClick} key={ind} /></div>
            )
        }</span>);
    }
}

【讨论】:

    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2019-08-06
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多