javascript – 如何在ReactJS中使用setState()方法?

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

>在构造函数内部
>在渲染方法OR中
>创建一个自定义方法,并在调用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;

解决方法:

如果在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>
上一篇:react——基础数据事件传输绑定(TodoList)


下一篇:vue 转react尝试