读取后未设置数据

问题描述 投票:0回答:1

此组件的我的代码使用的不是设置数据,而是使计数行正确(空)

import React,{Component} from'react'出口类Employ扩展了React.Component {

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

componentDidMount() {
    fetch("api/SampleData/GetEmpl")

        .then(res => res.json())
        .then(
            (result) => {
                this.setState({
                    employ: result
                });
            }
        );
}

render() {
    return (
        <div>
            <h2>Employ Data...</h2>
            <table className="table stripted bordered hover">
                <thead>
                    <tr>
                        <th>EmployeeID</th>
                        <th>FullName</th>
                        <th>EMPCode</th>
                        <th>Mobile</th>
                        <th>Position</th>
                    </tr>
                </thead>
                <tbody>
                    {this.state.employ.map(emp => (
                        <tr key={Math.random()}>
                            <td>{emp.EmployeeID}</td>
                            <td>{emp.FullName}</td>
                            <td>{emp.EMPCode}</td>
                            <td>{emp.Mobile}</td>
                            <td>{emp.Position}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}

}

I,m使用Asp.net.Api.core连接数据库(后端)谢谢

reactjs database api fetch connect
1个回答
0
投票

您可以使用setState作为回调函数。

import React, { Component } from 'react';

export class Employ extends Component {
    constructor(props) {
        super(props);
        this.state = {
            employ: []
        };
    }

    componentDidMount() {
        fetch("api/SampleData/GetEmpl")
            .then(res => res.json())
                .then(result => {
                    this.setState(() => ({
                        employ: result
                    }))
                })
    }

    render() {
        return (
            <div>
                ... YOUR JSX CODE GOES HERE ...
            </div>
        )
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.