繁体   English   中英

如何在使用钩子从子组件获取其值的父组件中更新正确的 state 值反应?

[英]How to update the correct state value in a parent component that gets its value from a child component using hooks in react?

我正在处理一个反应项目,并且使用当前正确的 state 值存在问题。 我在一个包含父组件和子组件的小型虚拟项目中重新创建了该问题。 Child 是从 Parent 组件传递下来的 props,一个 state 变量和一个 function 使用反应钩子(useState)更新所述 state。 在位于 Parent 组件中的原始 function 中,调用了第二个 function,它基于当前 state 执行操作。 我有控制台日志和结果显示传递下来的 function 发送回正确的值进行更新,但是下面的 function 不使用更新的值,而是似乎总是落后一个渲染。

我尝试使用 async/await 以及 useEffect 挂钩。 我已经能够在这个小型虚拟项目中使用 useEffect 的一些变化来获得“预期”结果,但是它并没有转化为实际项目,因为它们更多的 function 调用也取决于 state 值,尽管我可能只是误解/做错事。

export const Parent = () => {

    const [count, setCount] = useState(0);
    const [fruit, setFruit] = useState(null);

    const counter = (index) => {
        console.log("index passed in: ", index);
        setCount(index);
        secondMethod()
    }

    const secondMethod = () => {
        console.log('state of count in second method', count);
        const arr = ['apple', 'cherry', 'orange', 'kiwi', 'berry'];
        setFruit(arr[count]);
    }

    return (
        <div>
            <p>Hello from Parent, current count: {count}</p>
            <Child counter={counter} count={count}/>
            <p>result of second method: {fruit}</p>
        </div>
    );
}

export const Child = ({ counter, count }) => {
    return (
        <div>
            <p>Child comp</p>
            <button onClick={() => counter(count + 1)}>
                Click on send counter
            </button>
        </div>
    );
}

索引上的控制台日志值以及 { count } output 都是正确的。 来自 secondMethod 的控制台日志的结果,因此 setFruit 的 state 不正确,并使用来自后面一个渲染的 state? 因此 count 将显示为 1,但 secondMethod 仍将 count 显示为值 0,因此显示“apple”而不是“cherry”。 我感谢任何和所有帮助/建议,谢谢!

React state 更新操作是异步的,并且为提高性能而进行批处理。 不能保证console.log('state of count in second method', count); 将反映更新的 state。

方案1使用secondMethod中的index值作为参数传入

解决方案 2在更新count更新fruit ,使用useEffect挂钩。 secondMethod替换为:

useEffect(() => {
    console.log('state of count in useEffect', count);
    const arr = ['apple', 'cherry', 'orange', 'kiwi', 'berry'];
    setFruit(arr[count]);
}, [count, setFruit]);

暂无
暂无

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

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