最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React js changing state does not update component - Stack Overflow

programmeradmin3浏览0评论

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 ponent 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 ponent. 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 ponent so it would update.Thank you for your time;

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 ponent 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 ponent. 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 ponent so it would update.Thank you for your time;

Share Improve this question edited May 16, 2016 at 17:56 Brayniverse 2603 silver badges15 bronze badges asked May 16, 2016 at 17:05 AugustAugust 1,8195 gold badges24 silver badges40 bronze badges 2
  • 2 Use this.setState, don't mutate this.state. Also, you should do the users.map() in your render function. – Aaron Beall Commented May 16, 2016 at 17:13
  • I'm just sharing an idea: when I change one properties, I use this.setState({ errorUp : "red"}). Could be this? – Pierfrancesco Commented May 16, 2016 at 17:14
Add a ment  | 

2 Answers 2

Reset to default 13

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 ponent not re-rendering when the state variable is updated. What worked for me was to NOT call .map() inside the ponent'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>
);
发布评论

评论列表(0)

  1. 暂无评论