我有一個按鈕,當它被點擊它應該改變按鈕的顏色爲紅色,我通過改變狀態來更新組件的類來使它.red類更新顏色和之後4s它會恢復正常。但不知何故,它不會更新並重新渲染組件。 我的代碼:React js改變狀態不更新組件
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);
這是爲什麼可能是happening.And是有任何其他方式增加類的組件,以便將update.Thank您的時間;
使用'this.setState',不要改變'this.state'。另外,你應該在你的'render'函數中執行'users.map()'。 – Aaron
我只是分享一個想法:當我改變一個屬性時,我使用'this.setState({errorUp:「red」})''。可能是這個嗎? – Pierfrancesco