【问题标题】:How to return a promise from redux thunk action and consume it in component如何从 redux thunk 动作返回一个承诺并在组件中使用它
【发布时间】:2020-03-23 13:38:30
【问题描述】:

我正在使用 React+Redux+Redux Thunk + Firebase 身份验证。用 Typescript 编写代码。 我的行动是:

//Type for redux-thunk. return type for rdux-thunk action creators
type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  IStoreState, //my store state
  null,
  Action<userActionTypes>
>

export const signInWithEmailAndPasword =(email:string, pasword:string): AppThunk=>{
  return async (dispatch)=>{
    auth.signInWithEmailAndPassword(email, pasword).then(response=>{
      if(response.user){
        const docRef = db.collection("users").doc(response.user.uid);
          docRef.get().then(function(doc) {
            if (doc.exists) {
              const userData = doc.data(); //user data from firebase DB
               //if user exists in DB, dispatch
               dispatch({
                type: userActionTypes.SIGN_IN_USER,
                payload: userData
              })
              return userData;
            } else {
                // doc.data() will be undefined in this case
                console.log("No such document!");
            }
        }).catch(function(error) {
            console.log("Error getting document:", error);
        });
      }
    })
    .catch(err=> dispatch(setUserError(err.message)))
  }
}

我的登录组件,我将在其中分派上述操作:

import React, { useState } from 'react'
//some other imports
//...
//
import { useDispatch, useSelector } from 'react-redux';
import { signInWithEmailAndPasword } from '../../redux/actions/userActions';


interface ISignInState {
  email: string;
  password: string;
}
const SignIn = (props:any) => {

  const [values, setValues] = useState<ISignInState>({ email: '', password: '' })

  const dispatch = useDispatch();

  const handleInputChange = (e: React.FormEvent<HTMLInputElement>): void => {
    const { name, value } = e.currentTarget;
    setValues({ ...values, [name]: value })
  }

  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const { email, password } = values;
    dispatch(signInWithEmailAndPasword(email, password))
//// -> gives error: Property 'then' does not exist on 
//// type 'ThunkAction<void, IStoreState, null, Action<userActionTypes>>'
    .then(()=>{ 
      props.history.push('/');
      setValues({ email: '', password: '' })
    })

  }

  return (<div>Sign in UI JSX stuff</div>)

所以当我尝试在dispatch(signInWithEmailAndPasword(email, password)) 之后使用.then() 时,会出现错误Property 'then' does not exist on type 'ThunkAction&lt;void, IStoreState, null, Action&lt;userActionTypes&gt;&gt;' 那么我如何从 redux 操作中返回 promise 并在其上链接 .then() 呢?我一直认为 thunk 动作默认返回 Promise。 谢谢你的帮助 编辑: 临时解决方案是使用any 作为上述操作的返回类型:

export const signInWithEmailAndPasword = (email:string, pasword:string):any =>{
  return async (dispatch: any)=>{
    try {
      const response = await auth.signInWithEmailAndPassword(email, pasword)
      if(response.user){
        const userInDb = await getUserFromDB(response.user)
        dispatch(userSignIn(userInDb))
        return userInDb
      }
    } catch (error) {
      dispatch(setUserError(error.message))
    }
  }
}

但我不想使用any

【问题讨论】:

  • 你可以等待 thunk - 看起来它可能只是图书馆的打字错误?如果您只是在该函数中执行async/await 会怎样
  • 但是,理想情况下,thunk 操作会根据您传入的 then 调度另一个操作,而不是在您的组件中执行它。
  • 顺便说一句,thunk 真的很恶心,你正在使用承诺,但是嵌套它们而不是返回它们,你没有返回你的顶级承诺(这也是一个问题,即使打字稿错误不存在).....yikes all over.
  • 我只需要它在成功响应后重定向。

标签: javascript reactjs redux firebase-authentication redux-thunk


【解决方案1】:

只需在此行之前添加return:

auth.signInWithEmailAndPassword(email, pasword).then(response=>{

原来是这样:

export const signInWithEmailAndPasword =(email:string, pasword:string): AppThunk=>{
  return async (dispatch)=>{
    return auth.signInWithEmailAndPassword(email, pasword).then(response=>{

它应该工作。

【讨论】:

  • 我也试过了。它没有用。问题在于该操作的返回类型。我有它作为AppThunk。但是如果我使用 any ,问题就消失了,我可以在上面链接 .then()
  • 我对TS类型系统不熟悉,但我认为应该是Promise,例如Promise。
  • 当然 Promise 类型应该是你返回的 Promise 的类型,而不是 thunk。
【解决方案2】:

Thunk 返回函数,而不是 Promise。为此,您可以查看redux-promise。但老实说,如果你做这么复杂的事情,你最好使用redux-saga。

另一种方法是使用 redux-api-middleware 背后的概念来创建您自己的自定义 redux 中间件。我过去这样做是为了将消息队列连接到 redux。

【讨论】:

  • PS 在一个稍微相关的注释上,你可能会觉得这很有趣jrsinclair.com/articles/2017/…
  • 调度 thunk 不会返回函数,它会返回 thunk 返回的任何内容。介绍redux-saga 的陡峭学习曲线和疯狂的复杂性对于这样一个小问题来说是巨大的矫枉过正。
  • Tunks 只会导致无法维护的疯狂代码,该示例中有 10 级缩进! Sagas 非常直截了当,任何中等能力的程序员都可以在一天内掌握它们背后的概念。您将如何为该 Thunk 编写单元测试?
  • 缩进主要来自 IF 语句。我添加它们是为了避免 TS null 检查。该操作功能中有两个功能。一种用于登录,一种用于数据库检查。我可以再次将它们分开。但我会在解决我的主要问题后去做。
  • Tunk 不会导致疯狂的不可维护的代码 - 疯狂的不可维护的代码会导致疯狂的不可维护的代码(如 OP)。它并不是因为它是一个重击而无法维护。我从来没有遇到过对 thunk 进行单元测试的问题,将其保持在 7-10 行以内,你会没事的。
猜你喜欢
  • 2016-11-14
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 2019-09-22
  • 2017-10-30
  • 2019-08-14
  • 2017-11-14
相关资源
最近更新 更多