避免使用效果在首次加载时渲染?



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

我希望在我点击更新按钮之前看到詹姆斯和约翰在桌子上

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

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

你可以这样做,

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

在我看来,我认为您应该将更改数据逻辑放入 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"));

为了避免在第一页渲染时执行依赖项useEffect,您必须使用 -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>;
}

一个没有目标的useEffect只输入一次,也许有帮助,之后你可以只对更新进行useEffect。

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

相关内容

  • 没有找到相关文章

最新更新