我有以下 React 组件。
import React, { Component } from 'react';
class VesselDropdown extends Component {
constructor(props) {
super(props)
this.state = {
}
}
componentDidMount() {
fetch('http://localhost:3001/get/vessels')
.then(res => res.json())
.then((data) => {
this.setState({
vessels: data,
test: 'xyz'
})
})
.catch(console.log)
}
render() {
console.log(this.state);
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
<h1>Move the mouse around!</h1>
<p>The current mouse position is ({this.state.test})</p>
{
this.state.vessels.map(d => {
console.log(d);
return <div>test</div>
})
}
</div>
);
}
}
export default VesselDropdown;
我正在尝试渲染存储在状态中的一些数据。但我收到以下错误:
Cannot read property 'map' of undefined
如果删除以下代码,则不会出现错误,并且它会在浏览器中显示“xyz”。
{
this.state.vessels.map(d => {
console.log(d);
return <div>test</div>
})
}
问题:
你知道我做错了什么吗?为什么我无法从州获取船只
数据?
谢谢
更多信息:
GET http://localhost:3001/get/vessels
返回:
[{"vesselimo":9337626,"vesselname":"NYK CONSTELLATION"}]
最佳答案
在构造函数中设置容器的初始状态。
例如
this.state={
vessels:[]
}
这有助于执行 map 方法而不会引发未定义的错误
关于javascript - React - 无法呈现状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59810689/