gpt4 book ai didi

reactjs - 初始化时跳过 Hook 更改 (useEffect)

转载 作者:行者123 更新时间:2023-12-02 16:48:28 25 4
gpt4 key购买 nike

我创建了一个带有下拉菜单的功能组件。每次用户选择一个新值时,我都会向消费组件发送一个事件。我正在为选定的索引使用 Hook 。我意识到钩子(Hook)是异步工作的。选择新值时,旧值将发送到使用组件。所以我开始使用“useEffect”。但是 useEffect 有副作用,它会在变量初始化时被调用。无论如何告诉 REACT 不要在初始化时向 useEffect 发送事件,这样我就不会在初始化时发送选定的更改事件?您只是添加一个 bool 变量(如 hasBeenInit)还是​​有更智能的东西?

https://codesandbox.io/s/blissful-clarke-ky1nr?fontsize=14&hidenavigation=1&theme=dark

import React, { useState, useEffect } from "react";
import {
Dropdown,
DropdownToggle,
DropdownMenu,
DropdownItem,
Button
} from "reactstrap";

const DropdownPaging = props => {
const [selectedValue, setSelectedValue] = useState(10);
const [dropdownOpen, setDropdownOpen] = useState(false);
const [pageIndex, setPageIndex] = useState(0);

const toggle = () => setDropdownOpen(prevState => !prevState);

function dropDownChanged(val) {
setSelectedValue(val);
}

useEffect(() => {
triggerEventChange(selectedValue, pageIndex);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedValue, pageIndex]);

function pageIndexIncremented() {
setPageIndex(counter => counter + 1);
}

function pageIndexDecremented() {
if (pageIndex >= 1) {
setPageIndex(counter => counter - 1);
} else {
setPageIndex(0);
}
}

function triggerEventChange(take, index) {
if (props.valueChanged) {
props.valueChanged({ take: take, pageIndex: index });
} else {
}
}

return (
<div>
<table>
<tr>
<td>
<Button
outline
disabled={pageIndex === 0}
color="dark"
onClick={pageIndexDecremented}
>
&lt;
</Button>
</td>
<td>{pageIndex}</td>
<td>
<Button outline color="dark" onClick={pageIndexIncremented}>
&gt;
</Button>
</td>
<td>
<Dropdown isOpen={dropdownOpen} toggle={toggle}>
<DropdownToggle caret outline color="dark">
{selectedValue}
</DropdownToggle>
<DropdownMenu>
<DropdownItem onClick={() => dropDownChanged(10)}>
10
</DropdownItem>
<DropdownItem onClick={() => dropDownChanged(25)}>
25
</DropdownItem>
<DropdownItem onClick={() => dropDownChanged(50)}>
50
</DropdownItem>
<DropdownItem onClick={() => dropDownChanged(100)}>
100
</DropdownItem>
</DropdownMenu>
</Dropdown>
</td>
</tr>
</table>
</div>
);
};

export default DropdownPaging;

最佳答案

你可以使用 useRef 来模拟组件是否已经挂载,所以你的组件变成:

  const mounted = useRef(false);
const toggle = () => setDropdownOpen(prevState => !prevState);

function dropDownChanged(val) {
setSelectedValue(val);
}

useEffect(() => {
if (mounted.current) {
triggerEventChange(selectedValue, pageIndex);
} else {
mounted.current = true;
}

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedValue, pageIndex]);

更新沙箱:https://codesandbox.io/s/dropdownpager-urvrp

关于reactjs - 初始化时跳过 Hook 更改 (useEffect),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59615551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com