gpt4 book ai didi

javascript - React Hook - 在 componentDidMount 处触发多个 "useEffect"

转载 作者:行者123 更新时间:2023-12-03 07:24:23 26 4
gpt4 key购买 nike

我正在使用多个 useEffect Hook 来执行 componentDidMountcomponentDidUpdate 功能,但是,当组件加载时,我所有的 useEffect最初触发...

const testComp = () => {
const stateUserId = useSelector(state => { return state.userId; });
const [userId, setUserId] = useState(stateUserId);
const [active, setActive] = useState(false);
const [accountId, setAccountId] = useState();

useEffect(() => {
console.log('component did mount...');
}, [userId]);

useEffect(() => {
console.log('should trigger when userId changes...');
}, [userId]);

useEffect(() => {
console.log('should trigger when active changes...');
}, [active]);

useEffect(() => {
console.log('should trigger when accountId changes...');
}, [accounted]);

return (<div>...</div);
}

当我的组件挂载时,我会在那里看到所有那些控制台日志

component did mount...
should trigger when userId changes...
should trigger when active changes...
should trigger when accountId changes...

我怎么可能只让我的第一个 useEffect 触发,而其他三个只在依赖项发生变化时触发?

最佳答案

useEffect 不是 componentDidMountcomponentDidUpdate 的直接替代品。 Effect 将在每次渲染后运行,这就是您看到所有这些控制台日志的原因。根据React文档,useEffect的第二个参数表示

you can choose to fire them (effects) only when certain values have changed.

初次渲染后,如果再次渲染该组件,只会触发相应值变化的effects watch。

实现您想要的效果的一种方法是创建额外的变量来承载初始值,并在需要时在 useEffect 中进行比较。

const testComp = () => {
const initUserId = useSelector(state => { return state.userId; });
const stateUserId = initUserId;
const [userId, setUserId] = useState(stateUserId);

useEffect(() => {
console.log('component did mount...');
}, [userId]);

useEffect(() => {
if (userId !== initUserId) {
console.log('should trigger when userId changes...');
}

}, [userId]);

return <div>...</div>
}

关于javascript - React Hook - 在 componentDidMount 处触发多个 "useEffect",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63201408/

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