避免在首次加载时使用useEffect进行渲染?

时间:2019-08-17 01:49:24

标签: javascript reactjs react-hooks

我知道useEffect是componentDidUpdatecomponentDidMount的“组合”吗?但是由于我已经传递了dependency,为什么在第一次加载时仍然加载它?

import React, { useState, useEffect } from "react";
import { Button, Table, Column } from "antd";

const initData = [
  {
    id: 1,
    name: "James"
  },
  {
    id: 2,
    name: "John"
  }
];

function MyTable({ changeDataFlag }) {
  const [data, setData] = useState(initData);

  useEffect(() => {
    setData(
      data.map(o => ({
        id: "Titus",
        name: "Paul"
      }))
    );
  }, [changeDataFlag]);

  return (
    <Table dataSource={data} rowKey={data => data.id}>
      <Column title="Id" dataIndex="id" />
      <Column title="Name" dataIndex="name" />
    </Table>
  );
}

export default MyTable;

我希望在我单击“更新”按钮之前先在桌子上看到James和John

https://codesandbox.io/s/hello-antd-t29cs

3 个答案:

答案 0 :(得分:1)

默认情况下,useEffect首先运行,然后在依赖关系更改时运行。

您可以这样做

useEffect(() => {
    if(changeDataFlag){
      setData(
        data.map(o => ({
          id: "Titus",
          name: "Paul"
        }))
      );
    }
}, [changeDataFlag]);

答案 1 :(得分:0)

我认为,您应该将更改数据逻辑放入onclick事件中。 通常,单击按钮时,将从服务器获取数据并更改数据。


import React, { useState, useEffect } from "react";
import { Button, Table, Column } from "antd";

function MyTable({ data }) {
  return (
    <Table dataSource={data} rowKey={data => data.id}>
     <Column title="Id" dataIndex="id" />
     <Column title="Name" dataIndex="name" />
    </Table>
  );
}

export default MyTable;

import React, { useState, useEffect } from "react";
import { render } from "react-dom";
import "antd/dist/antd.css";
import MyTable from "./MyTable";
import { Button } from "antd";
const initData = [
  {
    id: 1,
    name: "James"
  },
  {
    id: 2,
    name: "John"
  }
];

const App = () => {
  const [changeDataFlag, setChangeDataFlag] = useState(false);
  const [data, setData] = useState(initData);
  return (
    <div>
      <Button
        type="primary"
        onClick={() => {
          setData(
            data.map(o => ({
              id: "Titus",
              name: "Paul"
            }))
          );
        }}
      >
        change data source
      </Button>
      <MyTable data={data} />
    </div>
  );
};

render(<App />, document.getElementById("root"));

答案 2 :(得分:0)

没有目标的useEffect仅输入一次,可能对您有所帮助,在您可以将useEffect仅用于更新之后

useEffect(() => {
    setData(
      data.map(o => ({
        id: "Titus",
        name: "Paul"
      }))
    );
  }, []);