首页 > 解决方案 > useState 未在子项初始调用后在父项中更新

问题描述

我有父/子关系,但是在孩子的初始呼叫后,父母的状态没有得到更新。

const Parent = () => {
  const [carouselIndex, setCarouselIndex] = useState(0);
  const [translateValue, setTranslateValue] = useState(0);

  const handleChangeHero = () => {
    console.log("I'm in the parent component"); // This line gets called successfully every time it's invoked from the child, so the child and parent seem to be communicating.
    setCarouselIndex(carouselIndex + 1); // carouselIndex gets updated correctly on the first call (going from 0 to 1), but on every subsequent call from the child, this line gets ignored.
    setTranslateValue(translateValue + -(slideWidth())); // Same problem with this line: gets called on the first invocation only, then gets ignored on subsequent calls.
  }

  return (
    <Child changeHero={handleChangeHero} />
  )
}

const Child = props => {
  const bind = useGesture( // from "react-with-gesture".
   ({
    args: [index],
    down,
    delta: [xDelta],
    distance,
    direction: [xDir],
    velocity,
  }) => {
    if (!down && (xDelta < -150 || xDelta > 150)) {
      handleChangeHero(); // Method gets called here, when the user releases the mouse click
      gone.add(index);
    };
  },
);
  const handleChangeHero = () => {
    console.log("I'm in the child component"); // This line is called successfully every time this handler is invoked in the child. It's part of a method from "react-with-gesture".
    props.changeHero();
  };
 return (<div>I'm a child</div>);
}

我怎么setCarouselIndex每次都被叫到?

标签: react-hooksreact-propsreact-state-management

解决方案


我使用 react-redux 编写了一个解决方案。我可以在 redux action 函数中跟踪轮播索引值,并document.body.clientWidth在 parent 中结合它来计算translate-x值。由于某些非常奇怪的原因,即使正在调用事件处理程序,父级中的状态也不会从子级更新(在子级返回语句之前)。


推荐阅读