中间组件逻辑只应用一次 React

Intermediate component logic only being applied once React

这里我通过一个中间组件通过 props 向上传递状态。中间组件有一个处理程序(onIntermediatePropsHandler)有一些逻辑 (常量格式化金额 = enteredAmount += 10;) 在传递的数据上执行。逻辑似乎只执行一次。这是为什么?

const Parent = () => {

  const onParentPropsHandler = amount => {
    console.log(amount)
  }

  return (
    <div>
      <Intermediate IntermediateToParent={onParentPropsHandler} />
    </div>
  )
}

const Intermediate = (props) => {

  const onIntermediatePropsHandler = enteredAmount => {
    const formatedAmount = enteredAmount += 10;
    props.IntermediateToParent(formatedAmount)
  }

  return (
    <div>
      <Child ChildToIntermediate={onIntermediatePropsHandler} />
    </div>
  )
}

export const Child = (props) => {
  const [index, setIndex] = useState(null)

  const onClickHandler = (index) => {
    setIndex(index + 1);
    props.ChildToIntermediate(index);
  }

  return (
    <div>
      <button onClick={() => onResetState(index)}>Reset Counter</button>
    </div>
  )
}

这给出了

的控制台日志

enter image description here

我不确定你想在这里实现什么。但是如果你想在子本地状态设置索引之前格式化索引,那么你应该在设置索引之前调用父函数,如下所示:

const Intermediate = (props) => {
  const onIntermediatePropsHandler = (enteredAmount) => {
    const formatedAmount = (enteredAmount += 10);
    props.IntermediateToParent(formatedAmount);
    return formatedAmount // Return the formated Amount to the children
  };

  return (
    <div>
      <Child ChildToIntermediate={onIntermediatePropsHandler} />
    </div>
  );
};

export const Child = (props) => {
  const [index, setIndex] = useState(null);

  const onClickHandler = (index) => {
    const updatedIndex = props.ChildToIntermediate(index); // You get the updated index
    setIndex(updatedIndex + 1);
  };

  return (
    <div>
      <button onClick={() => onClickHandler(index)}> Counter: {index}</button>
    </div>
  );
};

我不确定你想做什么。但是如果你想格式化更新后的索引,你应该在useEffect函数中调用parents函数,因为索引是异步设置的,所以你得到的是旧状态。所以您的子状态将如下所示:

  useEffect(() => {
    props.ChildToIntermediate(index); // Updated index value
  });

  const onClickHandler = (index) => {
    setIndex(index + 1);
  }

这样,在更新索引后,您将根据更新后的索引(不再使用旧状态)调用父函数