【发布时间】: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