【问题标题】:How to connect to class component without passing props typescript如何在不传递道具打字稿的情况下连接到类组件
【发布时间】:2020-06-01 14:45:11
【问题描述】:

我开始使用 TypeScript 学习 React,今天遇到了一个问题 - 我无法在不传递数据的情况下连接到组件。

例如

import React from 'react';
import './App.css';
import Header from './components/Header';
import { PostInterface } from './pages/Posts';
import { Route, Switch } from 'react-router-dom';
import FullPost from './pages/FullPost';
import { BrowserRouter } from 'react-router-dom';
import PostsContainer from './pages/PostsContainer';

const App: React.FC = () => {
  return (
    <div className="App">
      <BrowserRouter>
        <Switch>
          <Route exact path="/">
            <Header image="https://www.linagro.tn/images/slider/slides/1920x400/southern-alps-1920x400.png" text="posts" />
            <PostsContainer />
          </Route>
          <Route path="/posts/:id">
            <Header image="https://www.linagro.tn/images/slider/slides/1920x400/southern-alps-1920x400.png" text="post" />
            <FullPost text="Post" title="It's my post" createdAt={Date.now} author="noname" />
          </Route>
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

我想渲染 PostsContainer 而不传递任何道具,因为组件将使用 connect 和 react redux 获取道具

import React, { Component } from 'react'
import { connect } from 'react-redux'
import Posts from './Posts';

class PostsContainer extends Component {
    render() {
        return (
            <Posts posts={this.props.posts} />
        )
    }
}

const mapStateToProps = (state: any) => {
    return {
        posts: state.posts
    }
}

export default connect(mapStateToProps, null)(PostsContainer);

我收到两个错误:

类型'Readonly & Readonly'。 对象可能是“未定义”。

如何在不传递数据的情况下呈现 PostsContainer?

【问题讨论】:

    标签: reactjs typescript react-redux


    【解决方案1】:

    问题是您没有指定 PostsContainer 需要什么样的道具,所以默认情况下它假定它不使用任何道具。然后,当您尝试使用 mapStateToProps 向它传递 posts 道具时,打字稿会抱怨。

    修复方法是更新类型以包含一个帖子道具:

    interface PostsContainerProps {
      // not sure exactly what the type on the posts prop is, but assuming 
      // you have a Post type defined somewhere, maybe something like:
      posts: Post[],
    }
    
    class PostsContainer extends Component<PostsContainerProps> {
      // rest is unchanged
    

    【讨论】:

    • 但是我必须在 PostsContainer 中传递帖子,我应该从连接中获取数据
    • 您是否尝试按照我建议的方式更新类型?您的代码看起来可以与这些类型一起使用,包括您在没有任何显式道具的情况下呈现 &lt;PostsContainer /&gt; 的部分。 connect 的类型定义很聪明,可以知道哪些 props 需要从外部传入,哪些不需要。
    • 我把它改成了这个接口 PostInterface { title: string, text: string, createdAt?: any, author?: string } interface PostsContainerProps { posts: PostInterface[], }
    • class PostsContainer extends Component { render() { return ( ) } }
    • 你是说打字稿开始抱怨&lt;PostsContainer /&gt;?它给你的错误是什么?
    猜你喜欢
    • 2021-06-17
    • 2021-10-19
    • 2021-11-10
    • 2021-12-09
    • 2019-02-06
    • 1970-01-01
    • 2021-03-08
    • 2021-09-12
    • 2018-06-25
    相关资源
    最近更新 更多