Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js changing state does not update component

I have a button that when it's clicked it should change button color to red, I am doing that by changing state to update class of component to make it .red class thus updating color and after 4s it would turn back to normal.Yet somehow it does not update and re-render the component. My code :

import React from "react";
import ReactDom from "react-dom";

const app = document.getElementById("app");
class Layout extends React.Component{
constructor(props){
    super(props);
    this.users =[
            {
                name:"user1",
                world:"88",
            },{
                name:"user12",
                world:"882",
            },{
                name:"user13",
                world:"883",
            },{
                name:"user14",
                world:"884",
            },{
                name:"user14",
                world:"884",
            },{
                name:"user15",
                world:"885",
            },{
                name:"user16",
                world:"886",
            },{
                name:"user17",
                world:"8867",
            },{
                name:"user18",
                world:"8868",
            }
    ];
    this.ulist = this.users.map((user, i) => {
        var cName = i<5 ? "active":"nonActive";
        return <div key = {i} className = {cName}><h4>{user.name}</h4><p>{user.world}</p></div>;
    });
    this.state = {
        lastUser:4,
        firstUser:0,
        errorUp:"",
        errorDown: "",
    };
}
moveUp(){
        this.state.errorUp = "red";
        setTimeout(() =>{
            this.state.errorUp = "";
        },4000);
}
render(){
    return(
        <div>
        <i className={"fa fa-caret-up arrow "+ this.state.errorUp} aria-hidden="true" onClick = {this.moveUp.bind(this)}></i>
        <i className={"fa fa-caret-down arrow "+ this.state.errorDown} aria-hidden="true"></i>
        {this.ulist}
        </div>
    );
}
}
ReactDom.render(<Layout/>,app);

Why could this be happening.And is there any other way to add class to the component so it would update.Thank you for your time;

like image 600
August Avatar asked May 16 '16 17:05

August


1 Answers

you need to use this.setState({property:value})method instead of this.state.something = "value" to set the new state. this.state.errorUp = "red" won't work, because setting state is an asyncronous operation, and setState method was created for that purpose.

like image 75
nuway Avatar answered Nov 10 '22 06:11

nuway