javascript - 反应 setState 不重新渲染
问题描述
在下面的代码中,Test 的状态正在更新,但没有重新渲染。我已经更新了按钮单击更改的父状态,我希望它重新呈现包括按钮在内的整个组件。但它不会重新渲染按钮。需要帮助。这是一个测试代码,两个类都是必需的。
import React from 'react';
class Button extends React.Component {
constructor(props){
super(props)
this.state = {
id : props.id
}
}
render() {
console.log('Button state id is', this.state.id)
return(
<div>
'hi ' + {this.state.id}
<br/>
<button type='submit' onClick={this.props.handleSubmit}>
submit
</button>
</div>
)
}
}
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
id: 1
}
this.changeId = this.changeId.bind(this)
}
changeId() {
let id = this.state.id
console.log('parent state id is', id)
this.setState({
id: ++id
})
}
render() {
return(
<Button id={this.state.id} handleSubmit={this.changeId}/>
)
}
}
编辑:我已修改代码以删除明显的错误,例如未将changeId
函数传递给Button
编辑2:在这里找到解决方案:React Child Component Not Updating After Parent State Change componentWillReceiveProps
解决方案
要在子组件中重新呈现数字,您需要对代码进行以下更改:
在changeId函数中id的当前场景值是事件,所以你不能做++id。您必须将其更新为:
changeId() {
this.setState({
id: ++this.state.id
})
}
并且子组件要重新渲染 props 值,你必须倾听 props 是否有任何变化。为此使用 react 的 componentDidUpdate 生命周期。像这样:
componentDidUpdate(prevProps){
if (this.props.id !== prevProps.id) {
this.setState({id: this.props.id});
}
}
另一种方法是不要将 props.id 存储在子状态中。直接在渲染中使用它。
class Button extends React.Component {
render() {
return(
<div>
'hi ' + {this.props.id}
<br/>
<button type='submit' onClick={this.props.handleSubmit}>
submit
</button>
</div>
)
}
}
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
id: 1
}
this.changeId = this.changeId.bind(this)
}
changeId() {
this.setState({
id: ++this.state.id
})
}
render() {
return(
<Button id={this.state.id} handleSubmit={this.changeId}/>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />
推荐阅读
- sql - 使用具有年份数据类型的一列创建表
- r - 合并不同的单独文本行并按特定模式排序
- javascript - how to show text box when the value from combo box is selected for more than one
- math - 找到弹丸击中旋转圆的角度
- machine-learning - 分类器是如何分类的?
- sql-server - ASP.NET MVC 使用远程表调用存储过程
- node.js - 承诺不等待 firebase 查询完成并过早解决
- c# - 仅调试构造函数,不在发布模式下编译
- c - 如何用 goto 翻译 if .. else 语句?
- c++ - 如何使用 .sdf 文件修复 RDkit 中的“OSError:文件错误:输入文件错误”?