我意识到以前有人问过这样的问题,但从阅读这里的几个问答来看,似乎在很多情况下人们都建议使用 componentWillUpdate
但根据我对 React 的(非常)基本的理解,如果如果子组件受到影响,我 setState()
不会重新渲染吗?
这是我的 App 组件(显示正在设置的状态、更新状态 handleClick
的函数)、Display 组件(显示来自状态的当前输入)和一个显示数字的 Button 组件并传递给函数handleClick
:
this.State = {
calcValue: 0
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(val) {
this.setState({ calcValue: val })
}
render() {
return(
<div class="calcBody">
<Display currentValue={this.State.calcValue} />
<h1>Calculator</h1>
<div class="numPad">
<Button btn="num col1" operator={1} handleClick={this.handleClick.bind(this)} />
这是按钮组件:
class Button extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
/*the button when clicked takes the handleClick function and passes it props based on whatever number is pressed */
<button onClick={() => this.props.handleClick(this.props.operator)}>
<div class={this.props.btn}>{this.props.operator}</div>
</button>
)
}
}
最后,这是显示组件:
class Display extends React.Component {
constructor(props){
super(props);
this.props = {
currentValue: this.props.currentValue
}
}
render() {
return(
<h1>{this.props.currentValue}</h1>
);
}
}
我想知道为什么在调用 handleClick(val) 时它不更新?
最佳答案
您将状态定义为 this.State
这是不正确的 should be lowercased : this.state
:
this.state = {
calcValue: 0
}
此外,这一行:
this.props = {
currentValue: this.props.currentValue
}
没有多大意义,因为 props 是在外面传递的,component shouldn't change them .
关于javascript - React 子组件不会在状态更改时重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53439669/