我正在使用Redux和Typescript作为语言来创建React应用。我遵循此https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html的建议为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”类型的参数。 类型'((dispatch:Dispatch, 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属性:
答案 0 :(得分:0)
代替
const mapDispatchToProps = (dispatch: Dispatch<any>, ownProps:OwnProps): DispatchProps => ({
onClick: () => dispatch(changeFilter(ownProps.filter))
})
执行此操作
//in the import section
import { bindActionCreators } from "redux";
const mapDispatchToProps = (dispatch: Dispatch<any>, ownProps:OwnProps): DispatchProps => {
return bindActionCreators ({
changeFilter }),
dispatch
}
在您的情况下,mapDispatchToProps
返回的对象包含一个onClick函数,这不是预期的行为
答案 1 :(得分:0)
我在此post中找到了解决方案。有一个为通用Dispatch
定义的类型称为AnyAction
,它是redux库的一部分,因此mapDispatchToProps
应该是:
const mapDispatchToProps = (dispatch: Dispatch<AnyAction>, ownProps:OwnProps): DispatchProps => ({
onClick: () => dispatch(changeFilter(ownProps.filter))
})