【问题标题】:.map function in react not display any data反应中的.map函数不显示任何数据
【发布时间】:2021-06-01 09:50:53
【问题描述】:

我的反应代码如下:

import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { Link, NavLink } from 'react-router-dom';

interface AllEmployeeDataState {
    empList: EmployeeData[];
    loading: boolean;
}

export class AllEmployee extends React.Component<RouteComponentProps<{}>, AllEmployeeDataState> {
    constructor() {
        super();
        this.state = { empList: [], loading: true };

        fetch('api/Employee/Index')
            .then(response => response.json())
            .then(data => {
                this.setState({ loading: false });
                this.state.empList.push(data);
                console.log(this.state.empList);
            });

        this.handleEdit = this.handleEdit.bind(this);
    }

    public render() {
        let contents = this.state.loading
            ? <p><em>Loading...</em></p>
            : this.renderEmployeeTable(this.state.empList);

        return <div>
            <h1>Employee Data</h1>
            <p>
                <Link to="/Employee/Detail">Create New</Link>
            </p>
            {contents}
        </div>;
    }

    private handleEdit(id: number) {
        this.props.history.push("/Employee/Detail/" + id);
    }

    private renderEmployeeTable(empList: EmployeeData[]) {
        return <table className='table'>
            <thead>
                <tr>
                    <th>EmployeeId</th>
                    <th>Name</th>
                    <th>Gender</th>
                    <th>Designation</th>
                    <th>City</th>
                </tr>
            </thead>
            <tbody>
                {empList.map((emp, i) => (
                    <tr key={i}>
                        <td>{emp.FldId}</td>
                        <td>{emp.FldName}</td>
                        <td>{emp.FldGender}</td>
                        <td>{emp.FldDesignation}</td>
                        <td>{emp.FldCity}</td>
                    </tr>
                ))}
            </tbody>
        </table>;
    }
}

export class EmployeeData {
    FldId: number = 0;
    FldName: string = "";
    FldFatherName: string = "";
    FldGender: number = 0;
    FldReligion: number = 0;
    FldCnic: string = "";
    FldDob: Date = new Date;
    FldCity: number = 0;
    FldPermanentAddress: string = "";
    FldContactNumber: string = "";
    FldNationality: number = 0;
    FldEmailId: string = "";
    FldStatus: boolean = false;
    FldDateOfJoining: Date = new Date;
    FldCreatedAt: Date = new Date;
    FldCreatedBy: number = 0;
    FldUpdatedAt: Date = new Date;
    FldUpdatedBy: number = 0;
    FldDesignation: number = 0;
    FldUsername: string = "";
    FldPassword: string = "";
}

但是当我运行代码时,它显示的是空白表。 现在我检查了浏览器控制台中的数据,“emp”和“emp.FldID”都显示了正确的数据。那为什么它没有显示在表格中? 当我将鼠标悬停在浏览器源选项卡中的 emp 上时,它显示完整的数据,但源选项卡中的单个 emp.FldId 未定义。

此外,如果我给出在构造函数中定义的硬编码数据,它在表格中显示得很好。

【问题讨论】:

  • 您的代码中加载状态为“假”的部分在哪里???我找不到它。如果没有,请尝试在构造函数中添加它...谢谢
  • 获取api数据时加载状态会设置为false。

标签: javascript json reactjs


【解决方案1】:

您创建状态的方式不正确

更换你的

this.state.empList.push(data);

this.setState({
   empList: data
})

【讨论】:

  • 请将 fetch 函数添加到 componentDidMount() 函数中,其中建议对组件进行 API 调用。接下来在你的render() 中添加一个调试器,并检查它是否在 API 响应一些 daa 后被调用
【解决方案2】:

在构造函数中触发 API 调用不是一个好习惯。请将您的 API 调用移至componentDidMount

componentDidMount() {
    fetch('api/Employee/Index')
      .then((response) => response.json())
      .then((data) => {
        this.setState({loading: false});
        this.setState({empList: data })
      });
  }

当你有一个状态作为对象或数组时,你不应该改变它。因为当 react 进行浅比较以检查状态是否更改时,它将无法识别更改,因为这样做 .push() 不会更改此处数组的引用。

【讨论】:

    【解决方案3】:
    componentDidMount(){
     fetch('api/Employee/Index')
                .then(response => response.json())
                .then(data => {
                    this.setState({ loading: false,empList:data});
                });
    console.log(this.state.empList);
    }
    

    【讨论】:

    • console.log(this.state.empList); 这不会记录数据。设置状态并立即记录它不会在 setState 中起作用,react 是异步的。
    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 2018-06-14
    • 2019-03-04
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    相关资源
    最近更新 更多