尽管 mapStateToProps 已通过 Typescript 仍要求传递道具

Typescript asking to pass props although being already passed by mapStateToProps

这是我的 ChildComponent 从 Redux 接收 foo prop。

interface InjectedProps {
  foo: string;
}

const ChildComponent: React.FC<InjectedProps> = ({ foo, }) => (
    <div>
      {foo}
    </div>
);

const mapStateToProps = (state: AppState): InjectedProps => ({
  foo: state.fooReducer.foo,
});

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

ChildComponentParentComponent 包装。

const ParentComponent: React.FC = () => (
  <div>
    <ChildComponent />
  </div>
);

Typescript 抛出一个错误来传递 foo 将自己作为 <ChildComponent foo="some value"/> 来传递,但我不想这样做因为它是由 Redux 隐式传递的。

Property 'foo' is missing in type '{}' but required in type 'Pick<InjectedProps, "foo">'.

如何解决这个问题?

确保像这样导入子组件:

import ChildComponent from './ChildComponent'

也像其他人一样建议安装 react-redux 类型(yarn add @types/react-redux -D 或 npm install @types/react-redux -D)。

如果这不起作用(它应该,但如果不起作用)你可以试试这个:

export default connect<InjectedProps>(mapStateToProps)(ChildComponent);

如果无法自动连接,您可以手动指定类型进行连接。

感谢您的精彩回复。我想通了。那么,如果您查看 ChildComponent.

的导出
export default connect(mapStateToProps, null)(ChildComponent);

我犯的错误是我指定了 null 因为 mapDispatchToProps 没有在这个组件中使用。我将其更改为 {} 并且打字稿不再引发错误。

所以 ChildComponent 导出应该是:

export default connect(mapStateToProps, {})(ChildComponent);