[英]How do I get updated state immediately when using setState?
I have a View
and Column
components.我有一个View
和Column
组件。 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.文档说,我可以使用useEffect
和columns
作为依赖项,并在下次渲染时更新长度。 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.