gpt4 book ai didi

javascript - React setState 不重新渲染

转载 作者:行者123 更新时间:2023-12-02 23:10:49 24 4
gpt4 key购买 nike

在下面的代码中,测试状态正在更新,但没有重新渲染。我已经更新了按钮单击更改时的父级状态,我希望它能够重新渲染包括 Button 在内的整个组件。但它不会重新渲染按钮。需要帮助。这是测试代码,两个类都是必需的

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 值为 event,因此您无法执行++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" />

关于javascript - React setState 不重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57370027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com