我使用 onMouseMove 事件来跟踪我的鼠标坐标。当我将这些坐标作为 Prop 发送到我的子组件并使用它们时, Prop 已经落后于我的实际鼠标坐标,但是当我尝试在我的主组件中使用它们时,它们是我的实际鼠标坐标。我可能在 componentDidUpdate 方法上犯了一个错误。有谁知道我的错误是什么?
主要组件
class Page extends React.Component {
state = {
XCoord: 0,
YCoord: 0
};
handleMouseMove = e => {
const XCoord = e.pageX;
const YCoord = e.pageY;
this.setState((state, props) => {
return { XCoord, YCoord };
});
};
render() {
const follower = this.refs.follower;
return (
<ThemeProvider theme={style}>
<div onMouseMove={e => this.handleMouseMove(e)} id="test">
<Head title="" />
<CreateGlobalStyle />
{this.props.children}
<Pointer coords={this.state} />
</div>
</ThemeProvider>
);
}
}
子组件
class Pointer extends React.Component {
componentDidUpdate(prevProps) {
this.positionElement(prevProps.coords.XCoord, prevProps.coords.YCoord);
}
positionElement = (x, y) => {
const mouse = {
x,
y
};
follower.style.top = mouse.y + "px";
return (follower.style.left = mouse.x + "px");
};
render() {
const follower = this.refs.follower;
return (
<Follower id="follower">
<Circle id="circle" />
</Follower>
);
}
}
最佳答案
欢迎来到 Stack Overflow!
快速浏览一下您的代码,您似乎在 componentDidUpdate
方法中使用了 prevProps
,这就是子组件中出现鼠标坐标的原因落后。您可能希望在 componentDidUpdate
方法中使用 this.props
而不是 prevProps
,如下所示:
警告:未经测试的代码!
componentDidUpdate() {
this.positionElement(this.props.coords.XCoord, this.props.coords.YCoord);
}
关于javascript - componentDidUpdate 的 props 速度不够快。如何修复它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55957896/