【问题标题】:React : Callback value received in parent not passing the latest value in another child as prop | Function component反应:父母收到的回调值没有将另一个孩子的最新值作为道具传递|功能组件
【发布时间】:2020-03-28 20:59:44
【问题描述】:

我正在使用函数组件:

我有 1 个父组件和 2 个子组件。

子 1 通过回调将数据传递给父级。在父级中,接收到回调值并使用setState 将其分配给一个变量,并正确发送给子 2。

但是,当 child 1 进行任何更改并通过回调将数据传递给 parent 时,Parent 不会将另一个子组件中的最新值作为 prop 传递。仍然显示旧值。

图解:

示例代码:

const ContainerComponent = (props) => {
    let [selectedCenterId, setSelectedCenterId] = useState("");

    const callbackFromServiceDetails = (centerId) => {
        setSelectedCenterId((selectedCenterId = centerId));
        console.log("Inside parent callback");
        console.log(selectedCenterId);
    };

  return (  
      <>
        <ChildComponent1 activeTab={activeTab} parentCallback={callbackFromServiceDetails}></ChildComponent1>
        {
            selectedCenterId !== "" ?
            <ChildComponent2 activeTab={activeTab} selectedCenterId={selectedCenterId}></ChildComponent2>
            :
            <></>
        }
      </>
   );
};

export default ContainerComponent;


========================================================================

const ChildComponent1 = ({centersNLocations, actions, ...props}) => {

    const nextButtonClick = e => {
        e.preventDefault();
        props.parentCallback(selectedCenter);
      };

    return (
        <>
        ...
        </>
    );
};



ChildComponent1.propTypes = {
  ...
};

function mapStateToProps(state) {
  return {
    ...
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: {
      ...
    }
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ChildComponent1);



=====================================

const ChildComponent2 = (props) => {
    let [centerId, setCenterId] = useState(props.selectedCenterId);
    console.log(centerId);

    return (
        <>
        ...
        </>
    );
};

export default ChildComponent2;

有什么想法会导致此类问题吗?

【问题讨论】:

  • 你能提供一些代码吗兄弟!
  • 添加相关部分代码
  • @JatinParmar 添加了示例代码
  • 我已经测试了你的代码,它工作正常
  • 不知何故在第二次更改中没有传递正确的值

标签: reactjs callback setstate react-props react-functional-component


【解决方案1】:

我相信问题出在父组件代码中,因为您将引用从 useState 更改为值本身。 setSelectedCenterId((selectedCenterId = centerId));不应该 使用 equal 运算符,所以你的函数应该如下所示:

  const callbackFromServiceDetails = (centerId) => {
        setSelectedCenterId(centerId);
        console.log("Inside parent callback");
        console.log(selectedCenterId);
    };

未来提示:如果您想保持引用不变,请使用 const 而不是 let

【讨论】:

  • 我想要更新的值,因此放置 const 不会让数据改变,我希望这是正确的
  • 你可以有 const 并且它会在那里更新值,不用担心。但是您的主要错误是在代码中进行了分配,所以基本上这一行是错误的:setSelectedCenterId((selectedCenterId = centerId));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
  • 2018-03-29
  • 1970-01-01
  • 2019-08-21
相关资源
最近更新 更多