如何使用Redux Connect将类型传递给功能组件

时间:2019-05-13 05:47:20

标签: reactjs typescript redux

所以基本上,我的功能组件具有带有mapStateToProps和mapDispatchToProps的connect函数,但是如果我尝试访问props打字稿,则会抛出错误

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

1 个答案:

答案 0 :(得分:0)

在使用connect使TypeScript满意时,您需要指定类型:

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

位置:

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

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

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