【问题标题】:TypeScript Removing Repetitive Property Assignment with React-ReduxTypeScript 使用 React-Redux 删除重复的属性分配
【发布时间】:2020-06-22 20:35:05
【问题描述】:

我正在使用 TS React Redux,我的应用状态看起来像这样

type AppState = {
   foo: number
   bar: number
   baz: number
}

我有一个像这样连接到 redux 的组件

type ComponentState = {
   foo: number
   bar: number
}

function mapStateToProps(state: AppState): ComponentState{
   return {
      foo: state.foo,
      bar: state.bar
   }
}

我的问题是,在mapStateToProps 中,有没有办法复制道具而不必单独选择每个道具?由于ComponentStateAppState 的一个子集,我觉得有一种明显的方法可以做到这一点,但我错过了。

【问题讨论】:

    标签: reactjs typescript redux react-redux


    【解决方案1】:

    如果您同时使用 connect 和 TypeScript,我们特别建议使用 the ConnectedProps<T> pattern 来推断从 connect 传递到您的组件的所有道具的类型。如果您不想,这将消除编写 ComponentState 接口的需要,因为 TS 也会推断 mapState 的返回类型。

    您还应该考虑使用our useSelector hook in function components,因为它比connect 更容易输入。

    【讨论】:

    • 谢谢!我认为这与我正在寻找的最接近。仍然需要遍历某些属性,但 ConnectedProps 摆脱了一半。
    【解决方案2】:

    您可以解构您想要使用的项目,但是 mapStateToProps 函数是您定义从状态中取出什么以提供给组件的地方。

    function mapStateToProps({foo, bar}: AppState): ComponentState {
       return { foo, bar }
    }
    

    如果你想做一个更实用的方法,你可以这样做

    const myComponentKeys: Array<keyof ComponentState> = ['foo', 'bar']
    function mapStateToProps(state: AppState): ComponentState {
       return pick(myComponentKeys, state)
    }
    

    【讨论】:

    • 感谢您的建议!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 2019-01-30
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多