【发布时间】:2021-10-03 09:14:41
【问题描述】:
我正在尝试将数据从父组件传递给子组件,但数据的延迟会破坏我的代码。这是子组件,第二个是父组件。我做错了什么? 数据应该在 App.js 中渲染之前传递给孩子。如何解决?
问题出在 Grid 组件中的“const rows = objectProps”中。数据来迟了
import React from "react";
import { DataGrid } from "@material-ui/data-grid";
import "./Grid.css";
const Grid = ({objectProps}) => {
const rows = objectProps
const columns = [
{ field: "id", hide: true },
{ field: "empId1", headerName: "Employee ID#1", width: 150 },
{ field: "empId2", headerName: "Employee ID#2", width: 150 },
{ field: "projectId", headerName: "Project ID", width: 150 },
{ field: "days", headerName: "Days worked", width: 150 },
];
return (
<div className="data-grid-container">
<DataGrid rows={rows} columns={columns} />
</div>
);
};
export default Grid;
这是父组件
import React, { useState } from "react";
import './App.css';
import readLines from './helpers/calculateTeamDays'
import InputFile from "../src/components/input/InputFile";
import Grid from "../src/components/grid/Grid";
function App() {
const [state, setState] = useState({});
const [showGrid, setShowGrid] = useState(false);
const [none, setNone] = useState(false);
const addFile = (e) => {
let fileList = e.target.files;
let fileReader = new FileReader();
fileReader.onload = () => {
let linesArray = fileReader.result.split("\n")
let objects = readLines(linesArray);
objects.forEach((obj, i) => obj.id = i)
if (objects) {
setShowGrid(true)
setState(objects)
setNone(false)
console.table(objects)
} else {
setNone(true)
setShowGrid(false)
}
}
fileReader.readAsText(fileList[0])
}
return (
<div className="app">
<h1>Find two team members worked longest on project together</h1>
<InputFile add={addFile} />
{none ? <h2>No one worked in a team!</h2> : null}
{showGrid ? <Grid objectProps={state} /> : null}
</div>
);
}
export default App;
【问题讨论】:
-
最简单的方法是在渲染
Grid组件之前确保您的state对象不为空。showGrid可能在state对象被属性填充之前是true,因为所有这些useState更新函数都是异步的,并且取决于React如何批处理它们,您永远不能期望它们按顺序运行他们被称为。
标签: reactjs frontend use-effect use-state