首页 > 解决方案 > 在打字稿中设置反应类组件状态的默认值

问题描述

这是组件的状态:

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

标签: reactjstypescript

解决方案


totalPostsandpostPage应该是 type ,而不是andnumber的字面值。无法直接在接口上设置“默认值”,您必须在类本身的初始化中进行(看起来您已经在这样做了)。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 组件应该将状态和数据转换为要渲染的东西,而不是将组件的实例保存在变量或状态本身中,而是状态转换为渲染的组件。


推荐阅读