简体   繁体   English

使用 setState 时如何立即更新 state?

[英]How do I get updated state immediately when using setState?

I have a View and Column components.我有一个ViewColumn组件。 I use registerColumn method to store column refs in the View context:我使用registerColumn方法在View上下文中存储列refs

const [columns, setColumns] = useState([]);

const registerColumn = (node) => {
    const column = {
        someUniqueId: Math.random(),
        node,
        // more props
    };

    setColumns(prev => [...prev, column])
}

const context = {
    columns,
    registerColumn
}

<ViewContext.Provider values={context}>
    <View>
        <Column/>
        <Column/>
        <Column/>
    </View>
    <View>
        <Table/>
    </View>
</ViewContext.Provider>

Where I'm getting really confused is the Column component.我真正感到困惑的是Column组件。 Whenever I try to register the column and get the updated length afterwards, it's not being updated on time, because setState works asynchronously:每当我尝试注册该列并在之后获取更新的长度时,它都不会按时更新,因为setState是异步工作的:

const {columns, registerColumn} = useContext(ViewContext);
const ref = useRef(null);

useEffect(() => {
    registerColumn(ref.current);

    // Here is where updated column length but it keeps saying it's 0 length
    console.log(`Hello from column number ${columns.length}`);
}, []);

[...]

Docs are saying, that I can make use of the useEffect with the columns as the dependency and have the updated length on next render.文档说,我可以使用useEffectcolumns作为依赖项,并在下次渲染时更新长度。 However, I need to consume updated state right after registerColumn is invoked - using another useEffect will basically mean breaking execution context and the need to delay the task, plus possibly introduce other callbacks just to get around this.但是,我需要在调用registerColumn后立即使用更新的 state - 使用另一个useEffect基本上意味着破坏执行上下文和需要延迟任务,加上可能引入其他回调来解决这个问题。

I'm new to React but I'm pretty sure there are other possibilities to get around this, so any help will be greatly appreciated.我是 React 的新手,但我很确定还有其他可能解决这个问题,所以任何帮助都将不胜感激。

Updating setState in useEffect and console log in useEffect won't work, because useState works async and react batches all state and update it once.更新 useEffect 中的 setState 和 useEffect 中的控制台日志将不起作用,因为 useState 异步工作并且对所有 state 进行批处理并更新一次。 It is updating the state but it won't reflect that that monent because react batches with updates.它正在更新 state 但它不会反映那一刻,因为会通过更新对批次做出反应。
You can use other useEffect with dependency of columns, so every time registerColumn updates, second useEffect will be called and console log the value.您可以使用其他具有列依赖性的 useEffect,因此每次 registerColumn 更新时,都会调用第二个 useEffect 并控制台记录该值。

useEffect(() => {
    registerColumn(ref.current);
}, []);


useEffect(() => {
    console.log(`Hello from column number ${columns.length}`);
},[columns]);

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

相关问题 如何在 setState 回调中获取更新的状态? - How to get the updated state in setState callback? 如何使用 redux 立即更新 state? - How to get updated state immediately with redux? 在使用立即需要该状态的useState挂钩进行API调用时,如何等待setState调用结束? - How to await a setState call finishing when using useState hook that immediately needs that state to make an API call? setState()不立即改变状态 - setState() not mutating state immediately 为什么在我使用 React Hooks 调用 setState 之前,我的 state 会更新,我该如何修复禁用的鼠标指针? - Why is my state beeing updated before i call setState with React Hooks and how do i fix the disabled mouse pointer? 将状态和setState传递给组件时,如何更改状态? - How can I get the state to change when passing the state and setState to component? 当状态未立即更新时,ReactJS表单验证 - ReactJS form validation when state is not immediately updated 为什么会出现“在引用先前状态时在setState中使用回调”? - Why do I get “Use callback in setState when referencing the previous state”? 使用更新循环时如何在useEffect中获取更新状态 - How to get updated state in useEffect when using update loop 将 state 传递到 setState 时,我什么时候包含括号? - When do I include parenthesis when passing state into setState?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM