【前端】关于react+typescript遇到的“泛型约定组件状态”,报错:Property ‘***‘ does not exist on type ‘Readonly<{}>‘.ts,2339

typescript官方错误信息列表,简单说就是我们使用的state中的数据,必须要在一开始用泛型去规定一下类型,防止错误类型的数据传进来。

如果想深入了解,可以参考官方文档:typescript–泛型

接下来我说一下我的解决方法,我的解决方法是参考了这篇文章:原文链接,以下是我出现问题时的主要代码:

class ChapterList extends React.Component { constructor(prop) { super(prop) this.state = { // 章、节 chapter section chapterId:0, chapterName:'第五章', chapterContent: [ { sectionId: 0, sectionName: '第一节', subsectionNum: 2, subsection: [ { subsectionId: 0, subsectionName: '第一小节' }, { subsectionId: 1, subsectionName: '第二小节' } ] } ] } } handleClick = (e) => { console.log('click ', e); } render() { return ( <Menu onClick={this.handleClick} defaultSelectedKeys={['1']} defaultOpenKeys={['sub1']} mode="inline" > <div 150px", textAlign: "center", backgroundColor: "#2e92cd" }}> <h1 100px", fontSize: "30px" }}>{this.state.chapterName}</h1><br /> <h4 white" }}>一次函数</h4> </div> </Menu> ) } } 

改正之后的代码:

class ChapterList extends React.Component <{ navList ?: any }, { chapterId ?: number chapterName ?: string chapterContent ?: object } > { constructor(prop) { super(prop) this.state = { // 章、节 chapter section chapterId:0, chapterName:'第五章', chapterContent: [ { sectionId: 0, sectionName: '第一节', subsectionNum: 2, subsection: [ { subsectionId: 0, subsectionName: '第一小节' }, { subsectionId: 1, subsectionName: '第二小节' } ] } ] } } handleClick = (e) => { console.log('click ', e); } render() { return ( <Menu onClick={this.handleClick} defaultSelectedKeys={['1']} defaultOpenKeys={['sub1']} mode="inline" > <div 150px", textAlign: "center", backgroundColor: "#2e92cd" }}> <h1 100px", fontSize: "30px" }}>{this.state.chapterName}</h1><br /> <h4 white" }}>一次函数</h4> </div> </Menu> ) } } 

也就是在创建类的时候,规定一下state里数据的类型,可以自己对比一下。

总结:因为之前没有系统的看过typescript的文档,直接就上手了项目,导致现在遇到一些小问题,不过好在这些小问题网上都有现成的解决方案,把问题解决掉,总结下来,就变成了自己的东西,用项目去驱动学习,这样印象会更加深刻。就算我前期看了文档,估计实际写的时候也不会想到这个问题。