简体   繁体   中英

Cannot change state interface in react+typescript

In the bellow code, im getting a compilation error, I can't change in closeLeftCol the state: 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() {...}

}

Why am i able to change it in the contructore? what makes it read only? 在此处输入图片说明

Never mutate this.state directly , always use setState to update the state values.

Write it like this:

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

Other Places then constructor , you need to call setState method to change 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"
                }
            })
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM