【问题标题】:Redux + Typescript + funtional component: imported component requires props that come from ReduxRedux + Typescript + 功能组件:导入来自 Redux 的组件所需的 props
【发布时间】:2020-04-14 07:54:36
【问题描述】:

我有一个看起来像这样的组件:

  • 它有一个带有“alerts”属性的接口
  • 它连接到 Redux 并从 props 获取“警报”。

interface IAlert {
  alerts: { id: string; type: string; msg: string }[];
}

const Alert: FC<IAlert> = ({ alerts }) => {
  return (
    //does something with alerts
  );
};

Alert.propTypes = {
  alerts: PropTypes.array.isRequired
};

const mapStateToProps = (state: any): object => ({
  alerts: state.alerts
});

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

问题是: 当我将此组件(创建警报)导入另一个组件时,我得到这个:

Property 'alerts' is missing in type '{}' but required in type 'Pick<IAlert, "alerts">'.ts(2741)

我不想将“警报”传递给导入的元素,而只是从 Redux 中获取。

感谢您的帮助!

【问题讨论】:

    标签: javascript reactjs typescript redux react-redux


    【解决方案1】:

    使用@Jannis 的回答中的useSelector 挂钩更容易获得打字稿支持。

    可以使用connect 正确输入。您在这里没有得到它的原因是因为您的 mapStateToProps 函数的类型不正确。

    const mapStateToProps = (state: any): object => ({
      alerts: state.alerts
    });
    

    connect 使得组件的连接版本不再需要mapStateToPropsmapDispatchToProps 添加的道具。 但是那些道具是什么?mapStateToProps 的类型定义并没有说它返回一个 prop alerts。它只返回object

    返回 IAlert 会使您的错误消失,因为现在 connect 知道 alerts 属性已被提供。

    const mapStateToProps = (state: any): IAlert => ({
      alerts: state.alerts
    });
    

    如果您的state 有正确的类型而不是any,那么您根本不需要任何返回类型。对于这个特定的组件,您的IAlert props 类型实际上描述了所需的状态和返回。

    const mapStateToProps = (state: IAlert) => ({
      alerts: state.alerts
    });
    

    但通常你想从你的 store 或 reducer as described here 获取状态类型。

    export type RootState = ReturnType<typeof rootReducer>
    
    export type RootState = ReturnType<typeof store.getState>
    

    您需要在useSelector 中使用RootState,但有一个有用的快捷方式,因此您无需在每次使用时都指定类型。您可以创建自己的 useSelector 钩子 as explained here 的类型化版本。

    import { TypedUseSelectorHook, useSelector } from 'react-redux'
    export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
    

    所以现在你的组件不需要任何 props,并且 alerts 变量的类型是基于状态的类型而知道的

    export default () => {
    
      const alerts = useAppSelector(state => state.alerts);
    
      return (
        //does something with alerts
      );
    };
    

    【讨论】:

      猜你喜欢
      • 2017-09-16
      • 2019-12-29
      • 2023-03-27
      • 1970-01-01
      • 2023-04-04
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      相关资源
      最近更新 更多