首页 > 解决方案 > 如何定义redux thunk函数的mapDispatchToProps类型

问题描述

按照官方文档,我制作了一个类似 thunk 功能的登录打字稿。

function loginApi(user: UserState) {
  return fetch(
    `${baseUrl}/login?user=${user.userName}&pwd=${user.pwd}`
  )
    .then(res => res.json())
}

export const thunkLogin = (
  user: UserState
): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
  const asyncResp = await loginApi(user)
  dispatch(
    updateUser({
      loggedIn: asyncResp.isloggedIn,
      userName: user.userName,
      userPwd: user.userPwd
    })
  )
}

我想使用 react-redux connect hoc 函数将此 thunk 函数添加到我的应用程序组件中。

import { thunkLogin } from './thunkLoginPath'

interface Props {
  // place 1
  thunkLogin: typeof thunkLogin
}

interface State {
  userName: string
  userPwd: string
}

class AppComponent extends React.Component<Props, State> {
  handleSubmit = () => {
    this.props.thunkLogin({
      userName: this.state.userName,
      userPwd: this.state.userPwd
    })
  }

  render(){
    return(
      <TouchableOpacity
        style={style.loginBotton}
        onPress={this.handleSubmit}
      >
        <Text style={style.loginBottomText}>LOGIN</Text>
      </TouchableOpacity>
    )
  }
}

export default connect(
  (state: AppState) => ({
    user: state.user
  }),
  // place 2
  { thunkLogin }
)(AppComponent)

它报告一个错误表明 thunkLogin 在 Props 声明不能分配给 mapDispatchToProps (place 1 -> place 2)。

标签: typescriptreact-nativereduxreact-redux

解决方案


您是要连接 AppComponent 还是 Login 组件,因为您尝试从 AppComponent 调用 this.props.thunkLogin 但您连接了 Login。尝试像这样改变它。

export default connect(
  (state: AppState) => ({
    user: state.user
  }),
  // place 2
  { thunkLogin }
)(AppComponent)

推荐阅读