首页 > 解决方案 > 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

我将不胜感激任何建议,在此先感谢。

标签: reactjsreact-hooks

解决方案


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


推荐阅读