简体   繁体   English

React - 数据不使用 useEffect Hook 呈现

[英]React - data doesn't render using useEffect Hook

Description描述

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 以便它再次重新渲染?

Code代码

Parent Comp:家长比较:

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>
  );
};

Table Comp:表格比较:

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>
  );
};

What I've tried:我试过的:

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.谢谢你。

Sandbox Link沙盒链接

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.

相关问题 reactJS 在 useEffect 钩子中获取后不呈现数据 - reactJS doesn't render the data after being fetched in useEffect hook React useEffect 钩子没有清除间隔 - React useEffect hook doesn't clear interval React 在第一次没有渲染 useEffect - React doesn't render useEffect at the frist time 如何将子集合中的数据分配到其集合并呈现新对象? 使用 react、firebase 和 useeffect-hook - How to assign data from a subcollection to its collection and render the new object? Using react, firebase and useeffect-hook 使用反应 useEffect 钩子 - Using react useEffect hook 数组出现在 console.log() 中但不会在反应中呈现? 使用 useEffect 钩子 - Array is appearing in console.log() but will not render in react? Using useEffect hook 反应:暂停的组件不运行 useEffect 钩子 - React: Suspended component doesn't run the useEffect hook 当依赖项更改时,React useEffect hook 不会触发 - React useEffect hook doesn't trigger when a dependency changes 无法使用 React 中的 useEffect 钩子将 json 服务器数据连接到数组中 - Can't concatenate json server data into array using useEffect hook in React 使用 React useEffect 钩子刷新页面后无法将数据保存在 localStorage 上 - Can't persist data on localStorage after page refresh using React useEffect hook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM