我正在使用Redux和Typescript编写一个React Native应用程序。我一直在看别人的代码(我不能逐字共享),当他们使用connect
函数时,它看起来像这样:
export default connect<a, b, c, d>(
state => ({
...
}),
dispatch => bindActionCreators({
...
}, dispatch)
)(<Component name>)
谁能解释a, b, c, d
参数的用途是什么?我知道这涉及Typescript泛型,但是没有人能让我对connect
如何使用它们有更深入的了解吗?
谢谢!
答案 0 :(得分:0)
以下是带有ite接口的connect方法的详细信息:
<TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = {}>(
mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>
): InferableComponentEnhancerWithProps<TStateProps & TDispatchProps, TOwnProps>;
有关更多详细信息,请访问typescript-and-react-redux-connect
答案 1 :(得分:0)
在语法上这很冗长。
连接上的泛型被认为不会静态传递(尽管有一些例外。
bindActionCreators也不再是必需的,因为第二个参数对象的值将自动与dispatch绑定
即上述代码可以简化为...
const mapStateToProps(state: IGlobalState) => {
return {
// add things you want from your state here.
}
} // if you don't want anything from your state you can pass null.
export const withState = connect(mapStateToProps, {addTodo: TodoActions.add})(ComponentName)
export const withNoState = connect(null, {addTodo: TodoActions.add})(ComponentName)
export const withNeither = connect()(ComponentName) // at first glance looks useless but this will actually give you access to 'dispatch' inside your component.