无法更改状态界面反应+打字稿
问题描述:
在娄代码,即时得到一个编译错误,我不能在closeLeftCol更改状态: Cannot assign to leftWidth because it is a constant or read only property
:无法更改状态界面反应+打字稿
interface ILayoutState{
rightClassName: string,
leftClassName: string,
leftWidth: string,
rightWidth : string
}
export default class Layout extends React.Component<undefined, ILayoutState> {
constructor(props) {
super(props);
this.state = {
rightClassName: "right-col slide-in", leftClassName: "left-col slide-in", leftWidth: '' ,rightWidth : '' };
}
closeLeftCol() {
this.state.leftWidth = "0";
this.state.rightWidth = "100%";
this.state.leftClassName += " hideme";
this.state.rightClassName += " full";
this.forceUpdate();
}
render() {...}
}
答
Never mutate this.state directly,始终使用setState更新state
值。
写这样的:
closeLeftCol() {
this.setState(prevState => ({
leftWidth : "0",
rightWidth : "100%",
leftClassName : prevState.leftClassName + " hideme",
rightClassName : prevState.rightClassName + " full"
}));
}
答
其它地方则constructor
,你需要调用setState
方法来改变state
。
closeLeftCol() {
this.setState({
//change state here
leftWidth: "0",
rightWidth: "100%",
leftClassName: this.state.leftClassName + " hideme",
rightClassName: this.state.rightClassName + " full"
})
//or use this way
this.setState((prevState)=>{
return {
//change state here
leftWidth: "0",
rightWidth: "100%",
leftClassName: prevState.leftClassName + " hideme",
rightClassName: prevState.rightClassName + " full"
}
})
}
@AndrewLi是不是暗示?为什么我需要打印类型?它在继承时已经是decaler .. – Shazam