![](/img/trans.png)
[英]TypeScript Property 'navigation' is missing in type but required in type 'Props' React Native
[英]Property is missing in type '{}' but required in type… Typescript connect pattern
你好我需要连接模式来反应 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
如何解决这个问题?
正如我从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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.