React js更改状态不会更新组件

时间:2016-05-16 17:05:58

标签: javascript reactjs react-jsx

我有一个按钮,点击它时应该将按钮颜色更改为红色,我这样做是通过更改状态来更新组件的类来使它.red类因此更新颜色,4s之后它将恢复正常。但不知何故,它不会更新和重新渲染组件。 我的代码:

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

为什么会发生这种情况。还有其他方法可以将类添加到组件中以便更新。感谢您抽出时间;

1 个答案:

答案 0 :(得分:12)

你需要使用 this.setState({property:value})方法而不是this.state.something =“value” 设置新状态。 this.state.errorUp =“red”将不起作用,因为设置状态是异步操作,并且为此目的创建了setState方法。