在typescript中设置react类组件状态的默认值



这是组件的状态:

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,我还不能运行代码。

totalPostspostPage的类型应为number,而不是01的文字值。没有办法设置一个";默认值";直接在接口上,您必须在类本身的初始化中执行此操作(看起来您已经在执行了(。

对于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组件应该将状态和数据转化为要渲染的东西,而不是将组件的实例保留在变量或状态本身中,而是通过状态转换为渲染的组件。