无法在react + typescript中更改状态接口

时间:2017-05-31 07:03:47

标签: reactjs typescript

在下面的代码中,我得到一个编译错误,我无法在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() {...}

}

为什么我能在contructore中更改它?是什么让它只读? enter image description here

2 个答案:

答案 0 :(得分:1)

Never mutate this.state directly ,始终使用setState来更新state值。

像这样写:

closeLeftCol() {
     this.setState(prevState => ({
          leftWidth : "0",
          rightWidth : "100%",
          leftClassName : prevState.leftClassName + " hideme",
          rightClassName : prevState.rightClassName + " full"
     }));             
}

答案 1 :(得分:0)

其他地方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"
                }
            })
        }