javascript - React - 无法呈现状态值

标签 javascript node.js reactjs

我有以下 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/

相关文章:

reactjs - Webpack:./src/index.tsx 中的错误模块未找到:错误:无法解析 './App' 中的 '...'

javascript - 仅当不存在时才添加到 Realm 列表

javascript - 如何在不进行排序的情况下删除 Javascript 数组中的重复项

javascript - Node :Error 401(Unauthorized) i m using passport-jwt

node.js - 使用 sequelize 和环境变量连接数据库的 Node 配置文件设置

javascript - 如何修改react-redux connect 函数的默认名称?

javascript - 正则表达式匹配以特定字符串开头并以特定字符串结尾的字符串内容

javascript - Array.prototype 方法会影响函数中的多个变量吗?

node.js - Nodejs 导出和 module.exports : Why do we need exports anyway?

reactjs - React Router 认证路由问题