javascript 避免在第一次加载时使用效果进行渲染?

jaxagkaj  于 2023-01-11  发布在  Java
关注(0)|答案(4)|浏览(168)

我知道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

k5ifujac

k5ifujac1#

默认情况下,useEffect第一次运行,然后在依赖项更改时运行。
你能做到的

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

3j86kqsm2#

在我看来,我认为你应该把改变数据的逻辑放到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"));
4si2a6ki

4si2a6ki3#

为了避免在第一次页面呈现时执行dependencyuseEffect,必须将-useEffectuseRef一起使用。它仅在下一次更改时运行

import { useEffect, useRef, useState } from 'react';

function MyComponent() {
  const [data, setData] = useState('some data');
  const isFirstRender = useRef(true);

  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }
    console.log("This will not be called on first render");
  }, [data]);

  return <div>My Component</div>;
}
dkqlctbz

dkqlctbz4#

一个没有目标的useEffect只能输入一次,也许会有帮助,之后你可以使useEffect只用于更新

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

相关问题