>我创建了一个带有下拉列表的函数组件。每次用户选择新值时,我都会向消费组件发送一个事件。我正在为所选索引使用钩子。我意识到钩子是异步工作的。选择新值时,旧值将发布到使用组件。所以我开始使用"useEffect"。但是,useEffect 具有在初始化变量时调用它的副作用。有没有办法告诉 REACT 不要发送事件来使用初始化效果,所以我不会在初始化时发送选定的更改事件?您只是添加一个布尔变量(例如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}
>
<
</Button>
</td>
<td>{pageIndex}</td>
<td>
<Button outline color="dark" onClick={pageIndexIncremented}>
>
</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
布尔值是一个选项。如果您需要应用其他位置的行为,您可以创建自定义挂钩:
const useEffectIgnoringInit = (callBack, watchedValues) => {
const [hasBeenInit, setHasBeenInit] = useState(true);
useEffect(() => {
if(hasBeenInit){
callBack();
} else {
setHasBeenInit(true);
}
}, watchedValues);
}
然后你使用它而不是useEffect:
useEffectIgnoringInit(() => {
triggerEventChange(selectedValue, pageIndex);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedValue, pageIndex]);