typescript+react 能抽取公共state吗

自己写一个基类,然后业务子类继承此基类时state应该怎么设置比较好

 import * as React from 'react'
// 父类props
 interface ZooProps<T>{
     name:string;
     child:T;
 }
// 父类state
 interface ZooState<T>{
    age:number;
    child:T;
 }
// 父类
 class Zoo<T,S> extends React.Component<ZooProps<T>,ZooState<S>>{
    render(){
        return <p>{this.props.name}</p>;
    }
 }

 // 子类的props的类型
 interface AnimalProps{
     age:number
 }
// 子类state
 interface AnimalState{
     // 是否食肉
     isCarnivore:boolean;
 }

 class Tiger extends Zoo<AnimalProps,AnimalState>{

    componentDidMount(){
        // 此处设置感觉过于麻烦 子类的state前必须有一个child键值 不能直接更新某一个state
        this.setState({child:{...this.state.child,isCarnivore:true}})
    }
     render(){
         const name = this.props.name;
         const age = this.props.child.age;
         return null
     }
 }

如注释中所言 state既想抽取到父类中 同时又想把自己的state放到this.state 而不是this.state.child中,感觉自己的这种写法还是不合理 求解怎么做,后端基础比较差

阅读 3.3k
1 个回答

state本来就是组件专有的,react里面不推荐通过继承实现state复用,而是组合,就是组件的更小划分,分的更细。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题