简体   繁体   中英

How should one use the setState() method in ReactJS?

I'm new to ReactJS and I'm trying to understand state and setState() . Using setState() I wanted to change a name, but I am not sure where I should call the setState() method in my code:

  1. Inside the constructor OR
  2. Inside the render method OR
  3. Create a custom method and call it at the end of the constructor before render() is called

This is my code:

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;

If you call setState in render() method you will create infinite loop, instead you can use 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> 

setState usually occurs ( but it's not restricted to ) when there's some sort of interaction between the user and your application. For example:

  • When the user types in an input
  • When the user clicks a button

 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> 

For more information I recommend reading State and Lifecycle in ReactJS docs.

If you initializing the state then do in the constructor

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

If you want to change on some action then make a method ( changeName ) and use like this in render:

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>
        );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM