【发布时间】:2019-09-05 20:04:51
【问题描述】:
我正在使用 redux 和 typescript 作为语言创建一个反应应用程序。我按照post 的建议为mapStateToProps 和maptDispatchToProps 函数创建类型。这是我的容器:
import { connect } from 'react-redux'
import { AppState } from 'src/store';
import { changeFilter } from 'src/store/tasks/actions';
import { Dispatch } from 'redux';
import { VisibilityFilter } from 'src/store/tasks/types';
import * as React from 'react';
interface OwnProps {
filter: VisibilityFilter;
}
interface StateProps {
active: boolean
}
interface DispatchProps {
onClick: () => void
}
type Props = StateProps & DispatchProps & OwnProps
export const Filter: React.FC<Props> = props => {
const { active, onClick, children } = props;
return (
<button
onClick={onClick}
disabled={active}
style={{
marginLeft: "4px"
}}
>
{children}
</button>
);
};
const mapStateToProps = (state: AppState, ownProps: OwnProps): StateProps => ({
active: ownProps.filter === state.tasksState.visibilityFilter
})
const mapDispatchToProps = (dispatch: Dispatch<any>, ownProps:OwnProps): DispatchProps => ({
onClick: () => dispatch(changeFilter(ownProps.filter))
})
export default connect<StateProps,DispatchProps,OwnProps>(
mapStateToProps,
mapDispatchToProps
)(Filter)
但我在 connect 函数中遇到以下错误,对于 mapDispatchToProps 函数来说是这样的:
类型参数 '(dispatch: Dispatch, ownProps: OwnProps) => DispatchProps' 不可分配给“DispatchProps”类型的参数。 类型“(调度:调度, ownProps: OwnProps) => DispatchProps' 但在类型中是必需的 'DispatchProps'.ts(2345) Filter.tsx(17, 5): 'onClick' 被声明 这里。 Filter.tsx(49, 5):你的意思是调用这个表达式吗?
我的DispatchProps 类型是否有问题,connect 函数正在拒绝它?
如果您需要知道这些是我正在使用的库:
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-redux": "^7.0.2",
"react-scripts-ts": "3.1.0",
"redux": "^4.0.1"
},
"devDependencies": {
"@types/jest": "^24.0.11",
"@types/node": "^11.13.4",
"@types/react": "^16.8.13",
"@types/react-dom": "^16.8.4",
"@types/react-redux": "^7.0.6",
"typescript": "^3.4.3"
}
更新
如果我删除 connect 函数中的泛型类型,那么错误就会消失在这里,它会推断类型:
但是现在当我使用Filter 时,容器会强制我在定义中添加 onclick 属性:
【问题讨论】:
标签: javascript reactjs typescript redux react-redux