【问题标题】:How to define the mapDispatchToProps type of redux thunk function如何定义redux thunk函数的mapDispatchToProps类型
【发布时间】:2023-10-01 20:17:01
【问题描述】:

关注official doc,我做了一个类似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)

报错显示在 Props 中声明的 thunkLogin 不能分配给 mapDispatchToProps (place 1 -> place 2)。

【问题讨论】:

    标签: typescript react-native redux react-redux


    【解决方案1】:

    您的意思是连接 AppComponent 还是登录组件,因为您尝试 从 AppComponent 调用 this.props.thunkLogin 但您连接登录。 试着像这样改变它。

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

    【讨论】:

      【解决方案2】:

      您的mapDispatchToProps 完全没问题。如果你想在这里使用其他语法,你有:

      const mapDispatchToProps = (dispatch) => {
        return {
          thunkLogin: (user: UserState) => {
            dispatch(thunkLogin(user))
          }
        }
      }
      

      但我认为这不会帮助您解决 TypeScript 错误。至少我在 react-thunk 方面遇到了很多问题。我最终扔掉了所有 ThunkAction 废话,因为 TypeScript 足够聪明,可以识别函数类型。我只注意动作创建者的嵌套函数返回any。实际上它总是返回 void(但 TypeScript 不喜欢它)。你的函数看起来像这样:

      export const thunkLogin = (user: UserState) => async (dispatch): any => {
        const asyncResp = await loginApi(user)
        dispatch(
          updateUser({
            loggedIn: asyncResp.isloggedIn,
            userName: user.userName,
            userPwd: user.userPwd
          })
        )
      }
      

      这个解决方案对我来说已经足够好了,因为它显示我在组件中输入内容。我可以知道动作创建者是常规的还是thunk-powered。一个例子:

      如果您想了解更多有关 react-thunk 和 typescript 的信息,请访问此处: https://github.com/reduxjs/redux-thunk/issues/103

      【讨论】: