javascript - React 子组件不会在状态更改时重新渲染

标签 javascript reactjs

我意识到以前有人问过这样的问题,但从阅读这里的几个问答来看,似乎在很多情况下人们都建议使用 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/

相关文章:

javascript - 解析数据库中存储的json字符串以渲染D3树布局

javascript - 如何将 div 添加到 React Native?

javascript - JSFiddle 提供的额外 CSS

javascript - Angular 2-无法在组件声明中导入另一个组件

javascript - 设计模式 : Should repetitive function calls, 到不同的模块,是否被移动到自己的 "abstraction"?

javascript - ReactJS - 每 30 秒从父组件传递对象到子组件不起作用

reactjs - redux 和 immutable.js : putting non-serializable objects into state

reactjs - 从 React Native 中的 api 拦截器(组件外部)重定向到屏幕

javascript - 从另一个js函数触发Backbone事件

javascript - 如何使用 jquery/js/css 渐进地突出显示一大块文本