简体   繁体   中英

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;

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.

Even with useState, I've had issues with the component not re-rendering when the state variable is updated. What worked for me was to NOT call.map() inside the component's return statement, but instead invoke.map() within the setState function.

For example, given:

const { imgNums } = props;   // [123, 456, 789]
const [ myImages, setMyImages ] = useState( [] );

...This did NOT work:

setMyImages( imgNums.slice() );

return(
    <div>                                 
        {myImages.map((number, index) =>     
                         ( <img key={`${number}${index}`}            
                                src={`/images/${number}.jpeg`}       
                                alt='some description' /> ) ))
        }                                      
    </div>
);

...But this did:

setMyImages( imgNums.map((number, index) =>
    ( <img key={`${number}${index}`}
           src={`/images/${number}.jpeg`}
           alt='some description' /> ) ));

return(
    <div>                                 
        {myImages}                                      
    </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