【发布时间】:2019-02-28 06:15:16
【问题描述】:
谁能告诉我为什么,当我在 componentWillMount() 方法中设置状态时,render() 中的一个函数在设置状态之前运行,即
这是我的应用程序:
class App extends Component {
constructor(props){
super(props);
this.state={
x : 50,
y : 100,
width : 200,
height : 300
}
this.handleDuplicate = this.handleDuplicate.bind(this);
}
handleDuplicate(newDims){
this.setState({newDims : newDims})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<svg id="svgOne" width="5000" height="3000">
<NewRect
{...this.state}
handleDuplicate={this.handleDuplicate}
/>
</svg>
</div>
);
}
}
这是我的组件,NewRect:
import React, { Component } from 'react';
class NewRect extends Component {
componentWillMount(){
let { x, y, width, height } = this.props
let newDims = {
x : x + 30,
y : y + 30,
width : width - 50,
height : height + 50
}
this.props.handleDuplicate(newDims);
}
render() {
console.log(this.props);
return (
<rect
x={this.props.x}
y={this.props.y}
width={this.props.width}
height={this.props.height}
fill="black"
/>
);
}
}
export default NewRect;
据我所知,componentWillMount() 的全部意义在于完成所有需要在 render() 之前完成的操作。
【问题讨论】:
-
仅供参考,在 eact 16 中,componentWillMount 被认为是遗留的,并且可能会在某些时候消失,正是因为 ots 的正确用法一直被误解。
标签: reactjs components state