首页 > 解决方案 > 在反应中获取后未设置数据

问题描述

这是我的组件代码,employ它没有设置数据但得到正确的计数行(空)。

我想在从服务器端获取数据后设置数据。

import React, { Component } from 'react';

export class Employ extends 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>
        );
    }

}

我使用 Asp.net.Api.core 连接数据库(后端)。

标签: reactjsdatabaseapifetchconnect

解决方案


您可以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>
        )
    }
}

推荐阅读