React TypeScript应用报错:Type '{}'缺少Readonly类型属性求修复
错误原因
你遇到的这个错误,是因为Website组件的IProps接口定义了必填的属性:isAdmin、username,以及react-router-dom的RouteComponentProps包含的history、location、match。但你在使用这个组件时,要么是直接写<Website />没传任何属性,要么是没通过react-router的Route组件渲染,导致路由相关属性没自动注入,同时自定义的isAdmin和username也没提供,完全不满足IProps的类型要求。
修复方案
方案1:用react-router的Route组件渲染(推荐,适配路由场景)
如果这个组件是作为路由页面使用的,必须用Route组件包裹,通过render属性同时传递路由props和自定义props:
// 在你的路由配置文件中 import { Route } from 'react-router-dom'; import Website from './path/to/Website'; // 假设你有当前用户的信息数据 const currentUser = { isAdmin: true, username: 'your_username' }; // 配置路由时传递所有必填props <Route path="/" render={(routeProps) => ( <Website {...routeProps} // 自动注入history、location、match isAdmin={currentUser.isAdmin} username={currentUser.username} /> )} />
方案2:直接使用组件时手动传全所有props
如果不是作为路由页面使用,你得手动传入IProps要求的所有属性:
// 示例:手动传入所有必填属性 <Website isAdmin={false} username="guest" history={/* 这里需要传入有效的react-router history对象,比如从其他路由组件传递 */} location={{ pathname: '/', search: '', hash: '', state: null }} match={{ params: {}, isExact: true, path: '/', url: '/' }} />
这种方式比较繁琐,仅适用于非路由场景的特殊需求。
方案3:把非必须的props设为可选
如果某些属性不是组件运行的必备条件,可以在IProps里给它们加上?标记为可选:
interface IProps extends RouteComponentProps { isAdmin?: boolean; // 加?表示可选属性 username?: string; }
注意:设为可选后,在组件中使用this.props.isAdmin或this.props.username时,要处理它们可能为undefined的情况,比如用this.props.isAdmin ?? false来设置默认值。
内容的提问来源于stack exchange,提问作者user20819034
相关产品推荐
相关产品推荐

