我应该处理我的动作创建者中的错误吗 [英] Should I handle errors in my action creators

查看:28
本文介绍了我应该处理我的动作创建者中的错误吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下上下文中,我应该如何处理可能的错误:

In the following context how should I handle possible errors:

export async function testAction(data) {

    try {
        let response = await axios.get(`https://jsonplaceholder.typicode.com/todos/1`);
        return {
            type: 'TEST_ACTION',
            payload: response
        }
    } catch(err) {
        // ???
    }

}

//组件中的某处:

<Button onClick={ () => dispatch( testAction() ) }>
    Test Stuff
</Button>

或者更好地从组件实际调度,例如:

Or is better to actually dispatch from the component, eg:

重构动作创建者:

export async function testAction(data) {

        try {
            let response = await axios.get(`https://jsonplaceholder.typicode.com/todos/1`);
            return response
        } catch(err) {
            return err
        }

}

组件中的某处:

const handleTestAction = () => {
   testAction().then(r => dispatch( { type: 'TEST_ACTION', payload: r } ) ).catch( // hadnle errors)
}

<Button onClick={ handleTestAction }>
   Test Stuff
</Button>

我知道 redux 风格指南推荐使用 Action Creators 用于调度动作,但在这种特殊情况下,我首先调用动作,然后使用调度.我应该如何处理?

I know the redux style guide recommends using Action Creators for dispatching actions but in this particular case I am calling the action first and then use dispatch. How should I approach it?

推荐答案

您可以创建另一个 reducer 来处理错误.

You can create another reducer to handle errors.

   export async function testAction(data) {

        try {
            let response = await axios.get(`https://jsonplaceholder.typicode.com/todos/1`);
            return {
                type: 'TEST_ACTION',
                payload: response
            }
        } catch(err) {
            return {
                type: 'ERROR',
                payload: err
            }
        }

    }

但是你不能像上面那样做.因为过程是异步的

为此您必须使用redux-thunk".一旦你将它作为中间件添加到你的商店,你就可以让调度器进入你的动作创建器,这样你就可以在完成后在测试动作中调度任何东西.

You have to use a 'redux-thunk' for that. Once you add it as a middle-ware to your store, you can get the dispatcher in to your action creater, so you can dispatch anything in the test action after you complete.

所以你的 reducer 应该改为下面的那个,

So your reducer should change to the below one,

   export async function testAction(data) {

     return (dispatch) => {
        try {
            let response = await 
            axios.get(`https://jsonplaceholder.typicode.com/todos/1`);

            dispatch({
               type: 'TEST_ACTION',
                payload: response
           })
        } catch(err) {
            dispatch({
               type: 'ERR',
                payload: response
           })
        }           
     }

    }

更新

一旦连接中间件,就可以在动作创建器中使用dispatch,

Once you connect the middleware, you can use dispatch in the action creater,

const store = createStore(
    reducers,
    {},
    applyMiddleware(thunk)
);

你只需要像上面一样将 thunk 添加到 store.

You need to only add the thunk to the store just like above.

你可以通过像下面这样重构你的代码使其更清晰

You can make it more clear by refactor your code like below

export const testAction = () => async (dispatch) => {
     try {
            let response = await axios.get(`https://jsonplaceholder.typicode.com/todos/1`);
            dispatch({
               type: 'TEST_ACTION',
                payload: response
           })
        } catch(err) {
            dispatch({
               type: 'ERR',
                payload: response
           })
     }
}

如果您的 API 将在开发和生产模式下发生变化,您可以使用以下方式,

If your API is going to change in dev and prod modes, You can use below way,

应用程序中的某处,

 const axiosInstatnce = axios.create({
    baseURL: "https://jsonplaceholder.typicode.com",
    headers: {/* you can set any header here */}
  });

现在当您创建商店时,

const store = createStore(
 reducers,
 {},
 applyMiddleware(thunk.withExtraArgument(axiosInstatnce))
);

现在你可以得到 axiosInstance 作为你从 testAction 返回的函数的第三个参数.第二个参数给出了当前状态.

Now you can get the axiosInstance as the third argument of the function you return from the testAction. 2nd argument gives the current state.

 export const testAction = () => async (dispatch, state, api) => {
     try {
            let response = await api.get(`/todos/1`);
            dispatch({
               type: 'TEST_ACTION',
                payload: response
           })
        } catch(err) {
             dispatch({
               type: 'ERR',
                payload: response
           })
     }
}

现在在您的组件中,

import {testAction} from '../path/to/actions'

    const dispatch = useDispatch()

    dispatch(testAction())

这篇关于我应该处理我的动作创建者中的错误吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆