【问题标题】:React updating state within the same component在同一组件内反应更新状态
【发布时间】:2016-01-30 16:43:11
【问题描述】:

我是 react 新手,我认为设置 state 会重新渲染 react 组件。我在这里错过了什么吗,直到我致电this.forceUpdate() 后才会显示我的文字。

export default class Hello extends React.Component {
  constructor(props){
    super(props);
    this.state = { value: ''};
    this.handleChange = this.handleChange.bind(this);   
  }

  render() {
    return (
        <div>
            <input type="text" onChange={this.handleChange}   />
            <p> You entered {this.state.value} </p>
        </div>
    );
  } 

  handleChange(event){      
    this.state = { value: event.target.value };     
    this.forceUpdate();
  }
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您应该调用.setState 方法而不是为this.state 分配新值

    handleChange(event){      
      this.setState({ value: event.target.value })
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2016-01-19
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2015-05-21
      • 2021-10-22
      相关资源
      最近更新 更多