【问题标题】:Property is missing in type '{}' but required in type.... Typescript connect pattern类型“{}”中缺少属性,但类型中是必需的...... Typescript 连接模式
【发布时间】:2021-03-23 14:44:03
【问题描述】:

您好,我需要 react typescript 的连接模式

我有减速器

type State = {
  version: number,
  a?: string 
}


    interface ActionC {
      type: string
      payload?: number 
    }
    
    type IAction = ActionA | ActionB | ActionC;
    
    const reducer = (state: State = initialState, action: IAction) => {
      // The reducer normally looks at the action type field to decide what happens
      switch (action.type) {
        // Do something here based on the different types of actions
        default:
          // If this reducer doesn't recognize the action type, or doesn't
          // care about this specific action, return the existing state unchanged
          return state
      }
    }

但是当我绑定时使用连接

export const App: FunctionComponent<{ version: number}> = (props) => {

    return (
      <div>APP {props.version}</div>
    )
    }



const mapStateToProps = (state: State) => {
  return {
    version: state.version
  }
};

export default connect(mapStateToProps)(App);

我有错误

类型“{}”中缺少属性“版本”,但类型中是必需的 '省略'。 TS2741

如何解决这个问题?

【问题讨论】:

  • 除非你有意将 UI 与状态完全分离(这样做有充分的理由),否则你可以省去一些痛苦并采用useState 钩子而不是使用connect。现在你可以去掉connect HOC 的所有样板,你的组件体看起来像这样const version = useState(state =&gt; state.version); return &lt;div&gt;{version}&lt;/div&gt;。现在这容易多了。
  • @spender 我相信你的意思是useSelector,而不是useState
  • @NicholasTower 确实如此。谢谢指正。

标签: reactjs typescript redux


【解决方案1】:

正如我从https://redux.js.org/recipes/usage-with-typescript 拉出来的:

如果你还在使用 connect,你应该使用 @types/react-redux^7.1.2 导出的 ConnectedProps 类型来自动推断 connect 的 props 类型。这需要将 connect(mapState, mapDispatch)(MyComponent) 调用分成两部分:

import { connect, ConnectedProps } from 'react-redux'

interface RootState {
  isOn: boolean
}

const mapState = (state: RootState) => ({
  isOn: state.isOn
})

const mapDispatch = {
  toggleOn: () => ({ type: 'TOGGLE_IS_ON' })
}

const connector = connect(mapState, mapDispatch)

// The inferred type will look like:
// {isOn: boolean, toggleOn: () => void}
type PropsFromRedux = ConnectedProps<typeof connector>

type Props = PropsFromRedux & {
  backgroundColor: string
}

const MyComponent = (props: Props) => (
  <div style={{ backgroundColor: props.backgroundColor }}>
    <button onClick={props.toggleOn}>
      Toggle is {props.isOn ? 'ON' : 'OFF'}
    </button>
  </div>
)

export default connector(MyComponent)

【讨论】:

    猜你喜欢
    • 2020-08-24
    • 2021-07-26
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多