reactjs - 在打字稿中设置反应类组件状态的默认值
问题描述
这是组件的状态:
class Feed extends Component<FeedProps, FeedState> {
constructor(props) {
super(props);
this.state = {
isEditing: false,
posts: [],
totalPosts: 0,
editPost: null,
status: "",
postPage: 1,
postsLoading: true,
editLoading: false,
};
}
return (jsx code here)}
这是我写的界面:
interface FeedState {
isEditing: boolean;
posts: typeof Post[];
totalPosts: 0;
editPost: null | boolean;
status: string;
postPage: 1;
postsLoading: boolean;
editLoading: boolean;
}
我需要为 totalPosts 和 postpage 设置默认值,但我不知道。还
posts: typeof Post[]; // Post is a functional component and i try to say posts is gonna be array of Post instances. is it correct or shall I convert Post to class component.
我收到这些错误:
Types of property 'totalPosts' are incompatible.
Type 'number' is not assignable to type '0'.
Type '{ posts: React.FC<PostProps>[]; totalPosts: number; }' is not assignable to type 'FeedState | Pick<FeedState, "posts" | "totalPosts">'.
我正在将我的 js 项目转换为 tsx,但我还不能运行代码。
解决方案
totalPosts
andpostPage
应该是 type ,而不是andnumber
的字面值。无法直接在接口上设置“默认值”,您必须在类本身的初始化中进行(看起来您已经在这样做了)。0
1
至于Post[]
,在 React 中将 React 组件的实例直接保持在状态中是一种反模式。相反,您应该将这些实例表示的数据(模型)保持在状态,并以此为基础渲染组件。
所以不要这样做:
function Post({ title }) {
// etc.
}
// bad, very bad
this.setState({posts: [<Post title="Hello" />]});
// render function...
render () {
return <div>{this.state.posts}</div>
}
你应该做这个:
// much better
this.setState({posts: [{ title: "Hello" }] });
// render function...
render () {
return <div>{this.state.posts.map(ea => <Post {...ea} />)}</div>
}
然后在您的界面中,类型posts
将类似于Array<{title: string}>
,或者如果您想花哨,Array<Partial<React.ComponentProps<typeof Post>>>
React 组件应该将状态和数据转换为要渲染的东西,而不是将组件的实例保存在变量或状态本身中,而是将状态转换为渲染的组件。
推荐阅读
- mysql - mysql查询将字符串与int值进行比较
- ruby-on-rails - Rails - LoadError(无法加载此类文件 - json_web_token)
- sql - 避免在 SQL Server 过程中获取
- angular - 效果“AuthEffects.register$”发送了一个无效动作
- javascript - 上传文件时如何在服务器上获取表单数据值?
- clojure - YeSQL:哪个键需要值?
- java - 单击按钮时如何更改按钮颜色
- php - 连接时使用列作为表名
- excel - Outlook VBA 代码未退出
- javascript - Javascript - 过滤偶数