react-hooks - 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-redux 编写了一个解决方案。我可以在 redux action 函数中跟踪轮播索引值,并document.body.clientWidth
在 parent 中结合它来计算translate-x
值。由于某些非常奇怪的原因,即使正在调用事件处理程序,父级中的状态也不会从子级更新(在子级返回语句之前)。
推荐阅读
- jquery - 如何使用 jquery(wordpress)用 span 标签包装部分文本?
- java - AWS IoT 客户端:MqttException:连接意外关闭
- excel - Excel 文档自定义数字格式
- python - 为什么顺序在这个链式分配中很重要?
- mysql - kafka sink 从 mysql 到 postgres
- raspberry-pi - 更新 wpa_supplicant.conf 树莓派
- python - Selenium,不确定如何从通过 xpath 找到的元素中检索链接
- matlab - 使用 mldivide 约束参数
- node.js - Express/Mongoose 在单击时更新文档
- python - 如果语句不起作用并且没有意义