Javascript React组件在属性更改时不重新提交
我有两个文件:TrainingGround.js和Rectangle.js TrainingGround.jsJavascript React组件在属性更改时不重新提交,javascript,reactjs,Javascript,Reactjs,我有两个文件:TrainingGround.js和Rectangle.js TrainingGround.js 从“React”导入React; 从“/Rectangle”导入{Rectangle,RectangleComponent}; 导出类TrainingGround.Component{ 建造师(道具){ 超级(道具); 此.state={ rect:新的矩形(10,20,5,10,0), }; this.rotate=this.rotate.bind(this); } 轮换{ 该状态直
从“React”导入React;
从“/Rectangle”导入{Rectangle,RectangleComponent};
导出类TrainingGround.Component{
建造师(道具){
超级(道具);
此.state={
rect:新的矩形(10,20,5,10,0),
};
this.rotate=this.rotate.bind(this);
}
轮换{
该状态直接旋转(45);
log(this.state.rect.vertices);
}
render(){
返回(
);
}
}
当我调用this.state.rect.rotateDeg(45)
时,this.state.rect.vertices
的值被分配一个新数组(即数组不是简单地修改)。但是,这似乎不会触发矩形组件的重新加载。我可以使用下面的console.log()
语句确认此更改
Rectangle.js
。。。
导出类RectangleComponent扩展了React.Component{
获取polygonStr(){
//创建顶点的str,例如“1px2px,3px4px,…”
const verticesStr=this.props.vertices.map((e)=>e.map((f)=>f+'px').join(“”)).join(‘,’);
返回`polygon(${verticesStr})`;
}
render(){
返回(
);
}
}
在这种情况下,为什么不更新组件
这似乎是其他新开发人员面临的一个常见问题。我已经检查了其他类似的问题,但我仍在挠头为什么这不会更新 我的理解是,组件将在以下任一情况下重新启动:
- 它的状态改变了
- 它的性质改变了
除了其中一个的可变对象(在我上面的示例中不应该是这种情况)。尝试如下操作
rotate() {
const rect ={...this.state.rect}
rect.rotateDeg(45);
this.setState({rect});
}
不允许您像以前那样通过链接更新任何
此状态
React组件在两种情况下重新渲染自身:
a。更改任何状态属性(仅使用this.setState方法)
b。传递给此组件的任何道具都将更改
在您的示例中,您最好执行以下操作:
将矩形的实例放在这个.Rectangle中
可编辑值应位于此.state
内,并正确更改(仅通过此.setState
)
在组件更新时更新矩形实例
使用FC和hooks更容易做到这一点。更改旋转方法以设置新状态,而不是在状态中更改
rotate() {
// this.state.rect.rotateDeg(45); <-- Do not do this
const newRect = new Rectangle(10, 20, 5, 10, 45) //<-- Create new state
this.setState({rect: newRect}) //<-- Set new state
}
rotate(){
//该状态直接旋转(45);
rotate() {
// this.state.rect.rotateDeg(45); <-- Do not do this
const newRect = new Rectangle(10, 20, 5, 10, 45) //<-- Create new state
this.setState({rect: newRect}) //<-- Set new state
}