简体   繁体   English

从另一个“UseEffect”“调用”UseEffect

[英]'Calling' UseEffect from another 'UseEffect'

I'm learning react native and I'm programing a simple app to register the time of sleep of each day.我正在学习本机反应,并且正在编写一个简单的应用程序来记录每天的睡眠时间。

When the button that add the new register is pressed I do this当按下添加新寄存器的按钮时,我会这样做

onPress={() => setUpdateAction(true)}

That changes the value of the updateAction:这改变了 updateAction 的值:

const [updateAction, setUpdateAction] = useState(false); const [updateAction, setUpdateAction] = useState(false);

When the value of updateAction is changed this will be executed:当 updateAction 的值改变时,这将被执行:

useEffect(() => {

    ... code that add's the register to an array

    setviewInfoAction(true);
    setUpdateAction(false);
}, [updateAction]);

And inside I call setviewInfoAction(true);在里面我调用setviewInfoAction(true); becouse I want to change the value that is showed with the value that was inserted.因为我想更改显示的值和插入的值。

const [viewInfoAction, setviewInfoAction] = useState(false);


useEffect(() => {
        console.log("CALLED");
        var seted = false;
        for (var i = 0; i < registSleep.length; i++) {
            if (
                registSleep[i].day === selectedDay &&
                registSleep[i].month === selectedMonth &&
                registSleep[i].year === selectedYear
            ) {
                setSelectedDayHours(registSleep[i].hours);
                seted = true;
            }
        }
        if (!seted) {
            setSelectedDayHours(0);
        }
        setviewInfoAction(false);
    }, [viewInfoAction]);

Doing this I was expecting for the second UseEffect to executed but it's not...这样做我期待第二个 UseEffect 被执行,但它不是......

The way you have your useEffect set up it will only ever re-run if selectedDay changes.您设置 useEffect 的方式只会在selectedDay更改时重新运行。 If you want to make it run when setInfoViewAction is executed add viewInfoAction into the dependencies.如果你想让它在执行setInfoViewAction时运行,请将viewInfoAction添加到依赖项中。

Even better because all of this is related logic to the same sideEffect.更好的是,所有这些都是与同一个副作用相关的逻辑。 I would simplify your code by removing the second useEffect and adding the code inside it into the first useEffect .我会通过删除第二个useEffect并将其中的代码添加到第一个useEffect来简化您的代码。 This is mainly just because you can keep all related side effect logic together.这主要是因为您可以将所有相关的副作用逻辑放在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM