我从 vs2017 附带的 React+Redux 模板开始。我所做的只是尝试实例化一个“连接的”组件包装器。我的理解是,如果 connect 有效,那么当包装组件被实例化时,结果类型不应该期望任何东西通过 props 进入(因为到 props 的映射发生在内部)。然而,基于以下错误,它似乎在提示我没有通过 Prop 传递“计数”,但计数应该来 self 映射的 redux 存储。
错误 TS2322 (TS) 类型 '{}' 不可分配给类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }> & R...'。 类型“{}”不可分配给类型“只读”。 “{}”类型中缺少属性“count”。 WebApplication1 (tsconfig 项目) C:\Users\ben\Documents\Visual Studio 2017\Projects\WebApplication1\WebApplication1\ClientApp\components\FetchData.tsx 29 事件
状态定义:
export interface CounterState {
count: number;
}
连接调用:
export default connect(
(state: ApplicationState) => state.counter, CounterStore.actionCreators)(Counter) as typeof Counter;
我怀疑模板似乎正在将包装的连接组件类型转换为原始组件的形状,但我不确定这一点。
在这里实例化:
import Counter from '../components/Counter'
....
public render() {
return <div>
<Counter />
<h1>Weather forecast</h1>
我是否认为我可以实例化一个连接包装的容器组件而无需传递所需的 Prop ,因为它们应该来自 redux 存储,我是否错误?
更新:我已经在此处上传了可重现的测试用例:https://drive.google.com/file/d/0B_eEp0KGxixWN0tQTE1ac2FQYnc/view?usp=sharing
只需用VS2017 15.3.5打开解决方案,恢复node_modules后,可以运行解决方案查看错误,也可以打开文件ClientApp/Components/FetchData.tsx,错误如下显示在错误列表中。
最佳答案
as typeof Counter
确实是问题所在。通过将连接的组件键入 Counter
,您可以指定它仍然需要 count
属性,而它不需要。如果删除 typeof
,则 routes.tsx
中会出现错误,您可以通过安装最新的 types/react-router
来修复此错误( 4.0.15),它不再需要 Route
中的 component
拥有 RouteComponentProps
。您可能还想使用最新的 @types/react-redux
,以获得更准确的连接组件类型。
关于reactjs - React+Redux+ typescript : Error when trying to instantiate connect-wrapped component: Type {} is not assignable to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498919/