我正在使用用React构建的材料表(https://material-table.com/#/)。

我有数据作为物料表的支持,如下面的代码所示。
我通常单击父组件中的按钮以更改Performancetbl组件中的prop。但是,当我单击一次按钮时,表不会重新呈现新数据。当我再次单击它时,它会重新显示。为什么会这样呢?

我试图将props保存到Performancetbl组件中的状态变量状态,但这根本没有改变行为。

我还尝试console.log(props.datas)第一次单击该按钮时是否显示正确的数据。确实是正确的值!你们能弄清楚为什么会这样吗?

function Performancetbl(props) {
    const options = {
        ...
    };
    console.log(props.datas)
    return(
        <div style={{ maxWidth: "100%" }}>
            <MaterialTable
                title="Overall"
                data={props.datas}
                columns={props.columns}
                options={options}
                components={props.components}
            />
        </div>
    );
}

export default Performancetbl;


谢谢!

最佳答案

您最有可能发生这种情况的原因是,您是在数据到达之前渲染表的。

请参阅以下演示,了解如何从API获取数据并通过道具传递数据。

You can view a live demo here



ParentComponent.js

import React, { useState } from "react";
import AppTable from "./AppTable";

export default function ParentComponent() {
  const [tableData, setTableData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const columns = [
    {
      title: "Id",
      field: "id"
    },
    {
      title: "UserId",
      field: "userId"
    },
    {
      title: "Title",
      field: "title"
    },
    {
      title: "Completed",
      field: "completed"
    }
  ];

  const tableDiv = {
    marginTop: "30px"
  };

  const shadowStyle = {
    boxShadow: "0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)"
  };

  const btnStyle = {
    height: "40px",
    width: "300px",
    fontSize: "24px",
    cursor: "pointer",
    ...shadowStyle
  };

  const headStyle = {
    textAlign: "center",
    padding: "20px",
    backgroundColor: "lightcoral",
    ...shadowStyle
  };

  const sleep = time => {
    return new Promise(resolve => setTimeout(resolve, time));
  };

  const fetchData = async () => {
    setIsLoading(true);
    // Add a timeout to give the appearance of long load times
    await sleep(3000);

    try {
      const resp = await fetch("https://jsonplaceholder.typicode.com/todos");
      const json = await resp.json();
      setTableData(json);
    } catch (err) {
      console.trace(err);
      alert(err.message + "\r\n\r\nSee console for more info.");
    }
    setIsLoading(false);
  };

  return (
    <div>
      <div style={headStyle}>
        <h1>Click button to get data</h1>
        <button style={btnStyle} onClick={fetchData}>
          Click Me To Get API Data
        </button>
      </div>
      <div style={tableDiv}>
        <AppTable data={tableData} columns={columns} isLoading={isLoading} />
      </div>
    </div>
  );
}




AppTable.js(使用material-table

import React from "react";
import MaterialTable from "material-table";
import tableIcons from "./TableIcons.js";

export default function AppTable({ data, columns, ...rest }) {
  return (
    <MaterialTable
      {...rest}
      icons={tableIcons}
      columns={columns}
      data={data}
    />
  );
}

09-30 22:23
查看更多