首页 > 解决方案 > 反应 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

标签: javascriptreactjs

解决方案


要在子组件中重新呈现数字,您需要对代码进行以下更改:

在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" />


推荐阅读