React+Typescript 状态管理

好 本文 我们来说说状态管理 也就是我们的 state
我们直接顺便写一个组件 参考代码如下

import * as React from "react";

interface IProps {
    
    
    title: string,
    age: number
}

interface IState {
    
    
    count:number
}

export default class hello extends React.Component<IProps,IState> {
    
    

    public constructor(props:any){
    
    
        super(props);
    }

    public readonly state: Readonly<IState> = {
    
    
        count: 520
    }


    public render() {
    
    
        return (
            <div>
                <div>{
    
     this.state.count }</div>
            </div>
        )
    }
}

IProps 我们上文讲过 就是限制props 父组件传过来的值的

重点是IState 其实接口泛型都是一样的 创建一个接口 定义好名字 然后 声明里面有哪些字段 都是什么类型
然后 上文中 我们Component 传的是IProps 和 any 其实第二个要放state的限制规范
当然 如果你说 我们这个组件 如果不需要props 父组件不传值过来 可以这样

Component<any,IState>

如果说 我们这个组件不需要声明state 不用这里面的变量
可以这样

Component<IProps,any> {
    
    

就是 不需要就用 any
然后 我们根据IState接口的规范 创建了state
里面按接口规定 定义了一个数字类型的count
readonly 设置为只读属性

启动项目 效果是这样
在这里插入图片描述
this.state.count被成功输出

然后 就还是修改state中数据
我们先将组件改成这样

import * as React from "react";

interface IProps {
    
    
    title: string,
    age: number
}

interface IState {
    
    
    count:number
}

export default class hello extends React.Component<IProps,IState> {
    
    

    public constructor(props:any){
    
    
        super(props);
    }

    public readonly state: Readonly<IState> = {
    
    
        count: 520
    }

    clickHide(){
    
    
        this.setState({
    
    
            count: 200
        })
    }


    public render() {
    
    
        return (
            <div>
                <div>{
    
     this.state.count }</div>
                <button onClick = {
    
     this.clickHide }>修改</button>
            </div>
        )
    }
}

我们写了一个按钮 点击触发clickHide
clickHide中我们用了以前的setState去修改state中的count
运行项目之后 一切正常 但当我们触发事件
这里就会直接报错了
在这里插入图片描述
我们直接将代码改成这样

import * as React from "react";

interface IProps {
    
    
    title: string,
    age: number
}

interface IState {
    
    
    count:number
}

export default class hello extends React.Component<IProps,IState> {
    
    

    public readonly state: Readonly<IState> = {
    
    
        count: 520
    }
    
    public constructor(props:IProps){
    
    
        super(props);
        this.clickHide = this.clickHide.bind(this);
    }

    public clickHide(){
    
    
        this.setState({
    
    
            count: 200
        })
    }


    public render() {
    
    
        return (
            <div>
                <div>{
    
     this.state.count }</div>
                <button onClick = {
    
     this.clickHide }>修改</button>
            </div>
        )
    }
}

首先 其实就是 用bind 改变一下this的指向
在这里插入图片描述
我们再次点击这里 修改它就可以了

最后来和大家说一下这个readonly只读属性声明state的好处
例如 我们修改数据这样写
在这里插入图片描述
它可以阻止开发人员直接操作state中的字段 让代码更规范一些

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/132392343