reactjs - setState 的回调函数仅在渲染时将最后一个组件的状态填充到父组件的状态
问题描述
我有一个回调函数,以便将子组件的状态传递给父组件的状态。
当所有子组件加载时,我希望它们执行回调函数并填充父组件的状态。
尽管似乎只有最后一个组件将其状态传递给父组件。
我的子组件:
import React, { useState, useEffect } from "react";
export default function Component(props) {
const [state, setState] = useState(0);
useEffect(() => {
var index = props.index;
var stateSchema = {};
stateSchema[index] = state;
props.updateState(stateSchema);
}, [state]);
function onLeftClick() {
setState(state + 1);
}
return <p onClick={onLeftClick}>{state}</p>;
}
我的父组件:
import React, { useState, useEffect } from "react";
import Component from "./Component";
export default function ParentComponent() {
const [state, setState] = useState({});
function updateState(updatedState) {
setState({
...state,
...updatedState
});
}
useEffect(() => {
console.log(state);
}, [state]);
return (
<div>
<Component index="a" updateState={updateState} />
<Component index="b" updateState={updateState} />
<Component index="c" updateState={updateState} />
<Component index="d" updateState={updateState} />
<Component index="e" updateState={updateState} />
</div>
);
}
通常在控制台中我应该看到,
Object {e: 0, a: 0, b: 0, c: 0, d: 0}
但我明白了,
Object {}
Object {e: 0}
这是我的工作代码:https ://codesandbox.io/s/jovial-resonance-f085n?fontsize=14&hidenavigation=1&theme=dark
我将不胜感激任何建议,在此先感谢。
解决方案
setState
操作是异步的,并且为了提高性能而进行批处理。这在 setState 的文档中进行了解释。
setState() 不会立即改变 this.state 而是创建一个挂起的状态转换。在调用此方法后访问 this.state 可能会返回现有值。无法保证对 setState 的调用同步操作,并且可能会批处理调用以提高性能。
因此,在您的updateState
函数中,当它被调用时,状态尚未更新。
function updateState(updatedState) {
// state is {}
setState({
...state,
...updatedState
});
}
要使其正常工作,请更新您的代码,如下所示:
function updateState(updatedState) {
setState(prevState => ({
...prevState,
...updatedState
}));
}
更多关于这里的信息:https ://reactjs.org/docs/react-component.html#setstate
推荐阅读
- hyperledger-fabric - 如何在使用 fabric-mock-stub 测试链码时模拟两个链码
- c# - 从 Xamarin 表单中的 Listview 获取检查值
- java - java- ClassCastException- BigInt 不能转换为 Long
- centos - 坚持配置清漆
- bootstrap-4 - Bootstrap:不需要的手风琴行为
- git - 尝试将我的文件从 git 推送到 github 时出现错误,并发生此错误
- javascript - 如何使用外部 div 元素的 Onclick 事件
- go - 无论我是否关闭频道,地图缩小都不起作用
- c# - Linq 在同一个表中具有 case 条件,并在 where 条件下从其他表中计数
- mongodb - 无法对 Kubernetes 上的 mongodb 隐藏成员进行身份验证,“身份验证失败。”