您好,我需要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);
我有错误
类型“{}”中缺少属性“version”,但类型“Omit〈{ version:”中需要该属性数字; },永不〉'. TS 2741
如何解决此问题?
2条答案
按热度按时间jxct1oxe1#
当我从https://redux.js.org/recipes/usage-with-typescript中提取时:
如果你仍然使用connect,你应该使用@types/react-redux^7.1.2导出的ConnectedProps类型来自动推断connect中的属性类型。这需要将connect(mapState,mapDispatch)(MyComponent)调用拆分为两部分:
0md85ypi2#
函数connect必须有2个参数,而且必须始终有。即使你不使用mapDispatchToProps,你也必须传递它。在JS中可以使用null,而在TS中它应该是一个空对象。所以,你的代码应该是