【问题标题】:How to access async function from Redux Action passed into Redux Thunk?如何从传递给 Redux Thunk 的 Redux Action 访问异步函数?
【发布时间】:2018-08-18 13:26:27
【问题描述】:

我正在尝试将代码从 Javascript React 重构为 Typescript React。

我在这里有一个动作,它执行一个 API 调用并返回一个带有 dispatch 的函数

我的UserActions.ts 文件看起来像这样

export const login = ({username, password}) => async (dispatch: any) => {
  try {

    let r = await apiCall(); //performing api call here

    return r.code; //returning the custom responseCode here from my server

    console.log(auth)
  } catch (err) {
    throw new Error(err);
  }
}

在我的组件文件MyComponent.ts中有一个组件类的成员函数

public formSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        const { password, email } = this.state;

        this.props.login({
            email,
            password,
        }).then(responseCode => {
                //I want to access responseCode here
        });
}

MyComponent.ts 中与 Redux 的连接如下所示

const mapStateToProps = (store: IAppState) => {
    return {

    }
}

export default connect(mapStateToProps, {
    login
})(SignIn);

所以,如您所见,login 实际上返回了一个函数,该函数被传递到 Redux Thunk 中间件,然后在 this.props 中传递给 MyComponent

要从函数访问返回变量,我必须 type 登录操作中的外部函数 UserActions.ts

那么我如何使用正确的类型进行访问?因为打字稿不允许我将this.props.login().then() 放入MyComponent.ts

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    最佳实践是调度操作并将数据填充到减速器。尽量避免从异步函数传回数据。您可以拥有一个 AuthReducer 并更新数据并直接在组件中使用它。

    export const login = ({username, password}) => async (dispatch: any) => {
        let r = await apiCall(); //performing api call here
        dispatch({ type: 'UPDATE_AUTH', payload: auth })
    }
    

    在你的减速器中

    case 'UPDATE_AUTH':
     return { ...state, ...action.payload }
    

    在你的组件中

    const mapStateToProps = ({ auth }) => ({ auth })
    
    export default connect(mapStateToProps, {
        login
    })(SignIn);
    

    【讨论】:

      【解决方案2】:

      我不知道实际的 Typescript 方法,所以我使用了 any 解决方法

      而不是做

      this.props.login({
                  email,
                  password,
              }).then(responseCode => {
                      //I want to access responseCode here
              });
      

      你可以这样做

      const responseCode:any = await this.props.login({email, password});
      

      Typescript 在这里检查 await,我将返回的对象转换为 any,在运行时实际的 responseCode 从 Redux Thunk 返回

      【讨论】:

        猜你喜欢
        • 2021-12-11
        • 2023-03-23
        • 1970-01-01
        • 2016-09-22
        • 2020-02-05
        • 2017-01-12
        • 1970-01-01
        • 2018-01-31
        • 1970-01-01
        相关资源
        最近更新 更多