【问题标题】:How to pass types to a functional component in react using redux connect如何使用redux connect将类型传递给功能组件
【发布时间】:2019-05-13 05:47:20
【问题描述】:

所以基本上我的功能组件有 mapStateToProps 和 mapDispatchToProps 的连接功能,但是如果我尝试访问道具 typescript 会抛出错误

const Navbar: FC = ({ route, doChangeRoute }) => {
    //... code here bla bla 
}

const mapStateToProps = ({ routeReducer }: AppState) => {
    const { route } = routeReducer;
    return { route };
};

const mapDispatchToProps = dispatch => bindActionCreators({ doChangeRoute }, dispatch);

export default connect(
    mapStateToProps,
    mapDispatchToProps,
)(Navbar);

// ERROR: Property 'route' does not exist on type '{ children?: ReactNode; }'.  TS2339

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    你需要在使用 connect 时指定类型以使 TypeScript 快乐:

    export default connect<StateType, ConnectProps, OwnProps>(
        mapStateToProps, mapDispatchToProps
    )(Navbar)
    

    地点:

    StateType 是您的状态类型,如果您没有状态,则直接传递 {}

    ConnectProps 是连接将分配给您的组件的道具的类型

    OwnProps 是组件所期望的道具类型 不是来自连接

    【讨论】:

      猜你喜欢
      • 2019-10-08
      • 2017-05-13
      • 2019-08-20
      • 2019-12-13
      • 2021-11-13
      • 2017-04-28
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      相关资源
      最近更新 更多