【问题标题】:How should one use the setState() method in ReactJS?应该如何在 ReactJS 中使用 setState() 方法?
【发布时间】:2017-11-04 10:40:53
【问题描述】:

我是 ReactJS 的新手,我正在尝试理解 statesetState()。使用setState() 我想更改名称,但我不确定我应该在代码中的何处调用setState() 方法:

  1. 在构造函数内部或
  2. 在渲染方法内或
  3. 创建一个自定义方法并在构造函数末尾调用render()之前调用它

这是我的代码:

import React from "react";

class StateBasic extends React.Component{

    constructor(){
        super();
        let personProfile =  this.state = {
                name : "Bob",
                skill : "Art Designer",
                location : "LA"
        }
        console.log(personProfile);        
    }

    render(){
        let changeName =  this.setState({ name : "Frank" });

        return(
            <div className="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">   
                <ul>
                    <li> {this.state.name} </li>
                    <li> {this.state.skill} </li>
                    <li> {this.state.location} </li>
                    <li> {changeName} </li>
                </ul>
            </div>
        );
    }
}

// Let's render ReactDOM
export default StateBasic;

【问题讨论】:

    标签: javascript reactjs setstate


    【解决方案1】:

    如果您在render() 方法中调用setState,您将创建无限循环,您可以使用componentDidMount

    class StateBasic extends React.Component {
      constructor() {
        super();
        let personProfile = this.state = {
          name: "Bob",
          skill: "Art Designer",
          location: "LA"
        }
      }
    
      componentDidMount() {
        setTimeout(() => {
          this.setState({name: "Frank"});
        }, 1000)
      }
    
      render() {
        return ( 
          <div className="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
            <ul>
              <li> {this.state.name} </li>
              <li> {this.state.skill} </li>
              <li> {this.state.location} </li>
            </ul>
          </div>
        );
      }
    }
    
    ReactDOM.render( <
      StateBasic / > ,
      document.getElementById('container')
    )
    <script src="https://unpkg.com/react@16.0.0/umd/react.development.js"></script>
    <div id="container"></div>
    <script src="https://unpkg.com/react-dom@16.0.0/umd/react-dom.development.js"></script>

    【讨论】:

      【解决方案2】:

      如果你初始化状态然后在构造函数中做

      constructor(){
          super();
          let personProfile =  this.state = {
                  name : "Bob",
                  skill : "Art Designer",
                  location : "LA"
          }
          console.log(personProfile);
          this.state= { name : "Frank" };//initialvalue         
      }
      

      如果您想更改某些操作,请创建一个方法 (changeName) 并在渲染中像这样使用:

      changeName(name){
         this.setState({name})
      }
      
      render(){
      
              let changeName =  this.setState({ name : "Frank" });
      
              return(
                  <div className="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">   
                      <ul>
                          <li> {this.state.name} </li>
                          <li> {this.state.skill} </li>
                          <li> {this.state.location} </li>
                          <li onClick={this.changeName.bind(this,"hello")} > change Me </li>
                      </ul>
                  </div>
              );
          }
      

      【讨论】:

      • 嗨@Cyril,感谢代码解决方案。一个问题,经过 this.state= { name : "Frank" };//initialvalue 测试。我发现只有 name value Frank 显示在浏览器上,其他值(如技能和位置)为空白。如果我们在构造函数中使用 this.state 是否意味着它将覆盖对象的所有其他值?
      • 这只是构造函数中的一个示例,您可以定义第一个状态...设置名称只是一个示例。您也可以定义初始位置和技能。稍后您可以使用 setState 覆盖位置技能名称等。
      【解决方案3】:

      setState 通常在用户和您的应用程序之间存在某种交互时发生(但不限于)。例如:

      • 当用户输入时
      • 当用户点击按钮时

      class StateExample extends React.Component {
        constructor() {
          super()
      
          this.state = {
            clickTimes: 0,
            value: '',
          }
      
          this.handleChange = this.handleChange.bind(this)
          this.handleClick = this.handleClick.bind(this)
        }
      
        handleChange(event) {
          this.setState({ value: event.target.value })
        }
        
        handleClick() {
          this.setState({ clickTimes: this.state.clickTimes + 1 })
        }
      
        render() {
          return (
            <div>
              <label>Type here:</label>
              <input type="text" value={this.state.value} onChange={this.handleChange} />
              
              <div style={{ marginTop: 20 }}>
                <button onClick={this.handleClick}>Click-me</button>
                Click times: {this.state.clickTimes}
              </div>
            </div>
          )
        }
      }
      
      ReactDOM.render(
        <StateExample />,
        document.getElementById('root')
      )
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
      
      <div id="root"></div>

      有关更多信息,我建议阅读 ReactJS 文档中的 State and Lifecycle

      【讨论】:

        猜你喜欢
        • 2015-05-10
        • 1970-01-01
        • 1970-01-01
        • 2020-11-18
        • 2016-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-03
        相关资源
        最近更新 更多