[英]React - data doesn't render using useEffect Hook
Attempting to make a reusable table component by passing data as prop.尝试通过将数据作为道具传递来制作可重用的表格组件。 I'm making the api call in the parent component but the table won't render unless I make the api call in the table component itself or if I update the state of the object manually.
我正在父组件中进行 api 调用,但表格不会呈现,除非我在表格组件本身中进行 api 调用,或者如果我手动更新 object 的 state。 Is there a way to render the data being passed through or change the state of the object so that it re-renders again?
有没有办法渲染正在传递的数据或更改 object 的 state 以便它再次重新渲染?
const ParentComp = () => {
const [products, setProduct] = useState([]);
const fetchFakeData = () => {
TestService.getFakeData()
.then((res) => {
console.log(res.data);
setProduct(res.data);
})
.catch((err) => {
console.log(err);
});
};
useEffect(() => {
fetchFakeData();
}, []);
const productsData = useMemo(() => [...products], [products]);
const productColumns = useMemo(
() =>
products[0]
? Object.keys(products[0])
.filter((key) => key !== "rating")
.map((key) => {
return { Header: key, accessor: key };
})
: [],
[products]
);
return (
<div style={{ height: "80vh", paddingTop: "80px" }}>
<Container>
<Row>
<h3 style={{ textAlign: "left" }}>Data Table Example</h3>
<DataTableReuse myData={productsData} myColumns={productColumns} />
</Row>
</Container>
</div>
);
};
const DataTableReuse = ({ myData, myColumns }) => {
const [products, setProduct] = useState([]);
useEffect(() => {
setProduct(myData);
}, [products]); // I manually remove and add products here manually and table will display
const productsData = useMemo(() => [...products], [products]);
const productColumns = useMemo(
() =>
products[0]
? Object.keys(products[0])
.filter((key) => key !== "rating")
.map((key) => {
return { Header: key, accessor: key };
})
: [],
[products]
);
const tableInstance = useTable({
columns: productColumns,
data: productsData,
});
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
tableInstance;
return (
<div style={{ overflowY: "scroll", height: "600px" }}>
<Table striped bordered hover {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<th {...column.getHeaderProps()}>{column.render("Header")}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => {
return (
<td {...cell.getCellProps()}>{cell.render("Cell")}</td>
);
})}
</tr>
);
})}
</tbody>
</Table>
</div>
);
};
When I run the app locally and navigate to the page with the table component, the table will render if I remove products
from the useEffect brackets or if I add it back in. But once I reload the page it goes back to being a blank table.当我在本地运行应用程序并导航到包含表格组件的页面时,如果我从 useEffect 括号中删除
products
或将其重新添加,表格将呈现。但是一旦我重新加载页面,它就会恢复为空白表格. I'm assuming this is because the products
object is empty when the component renders but not sure why that's the case when I'm setting the data from prop in the useEffect hook.我假设这是因为当组件呈现时
products
object 是空的,但不确定为什么当我在 useEffect 挂钩中设置来自 prop 的数据时会出现这种情况。
Any help would be appreciated to help understand the component lifecycle here.任何帮助将不胜感激,以帮助理解此处的组件生命周期。 Thank you.
谢谢你。
https://codesandbox.io/s/awesome-bell-d5w0fe?file=/src/DataTableReuse.jsx https://codesandbox.io/s/awesome-bell-d5w0fe?file=/src/DataTableReuse.jsx
I was able to solve this by playing around with the useEffect hook.我能够通过使用 useEffect 钩子来解决这个问题。 I tried not using the useEffect hook at all as suggested by someone but the data.table wouldn't render if I didn't set my props as state. What I ended up doing was using the useEffect hook and added my prop as useEffects second argument instead of the new state object.
我尝试完全不按照某人的建议使用 useEffect 挂钩,但是如果我没有将道具设置为 state,data.table 将不会呈现。我最终做的是使用 useEffect 挂钩并将我的道具添加为 useEffects 第二个参数新的 state object。
const DataTableReuse = ({ myData, myColumns }) => {
const [products, setProduct] = useState([]);
useEffect(() => {
setProduct(myData);
}, [myData]); // made this watch the myData prop instead of products state.
If anyone has any suggestions on improving or if there is a better way to handle this.如果有人对改进有任何建议,或者是否有更好的方法来处理这个问题。 Please feel free to reply with an answer.
请随时回复一个答案。 Thanks all.
谢谢大家。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.