首页 > 解决方案 > TypeError:this.state.employees.map 不是函数

问题描述

在这里,我使用状态中的员工作为对象。

map is not a function尝试将其呈现为表格时出现此错误。后端 api 正在返回employees.

class Employee extends React.Component{

    constructor(props){
        super(props);
        this.state={
            employees:[]
        };
    }

        componentDidMount(){
            fetch("http://localhost:8080/employee/getEmployees").then(res=>res.json).then(
                result=>{
                    console.log(result.id)
                    this.setState({employees:result});
                }
            )
        }

    render(){
        return (<div>
            <h2>welcome to employee.</h2>

            <table>
                <thead>
                <tr>
                <th>Employee id</th>
                <th>Employee name</th>
                <th>Employee age</th>
                <th>Employee companyid</th>
                <th>Employee stream</th>
                </tr>
                </thead>
                <tbody>
                {this.state.employees.map(emp=>(

                <tr key={emp.id}>
                    <td>{emp.id}</td>
                    <td>{emp.name}</td>
                    <td>{emp.age}</td>
                    <td>{emp.companyId}</td>
                    <td>{emp.stream}</td>
                </tr>
                ))}
                </tbody>
            </table>
        </div>)

    }
}

ReactDOM.render(<Employee />, document.getElementById("root"))

标签: reactjs

解决方案


您正在将一个函数传递给第二个then未解析为 JSON 的结果。

只需更改res=>res.jsonres=>res.json().


推荐阅读