Reactjs 我应该处理动作创建者中的错误吗

Reactjs 我应该处理动作创建者中的错误吗,reactjs,react-redux,Reactjs,React Redux,在以下上下文中,我应该如何处理可能的错误: export async function testAction(data) { try { let response = await axios.get(`https://jsonplaceholder.typicode.com/todos/1`); return { type: 'TEST_ACTION', payload: response

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

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>
const handleTestAction = () => {
   testAction().then(r => dispatch( { type: 'TEST_ACTION', payload: r } ) ).catch( // hadnle errors)
}

<Button onClick={ handleTestAction }>
   Test Stuff
</Button>
组件中的某个位置:

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

<Button onClick={ handleTestAction }>
   Test Stuff
</Button>
constHandleteStation=()=>{
testAction().then(r=>dispatch({type:'TEST_ACTION',payload:r})).catch(//hadnle errors)
}
测试材料

我知道redux风格指南建议使用分派操作,但在这种特殊情况下,我首先调用操作,然后使用分派。我应该如何处理它?

您可以创建另一个减速机来处理错误

   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
            }
        }

    }
但是你不能像上面那样做。因为这个过程是异步的

你必须用“重击”来达到这个目的。一旦您将其作为中间件添加到存储中,您就可以将dispatcher放入您的action creater中,这样您就可以在完成测试操作后分派测试操作中的任何内容

所以你的减速器应该换成下面的

   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
           })
        }           
     }

    }
更新

连接中间件后,可以在action creater中使用dispatch

const store = createStore(
    reducers,
    {},
    applyMiddleware(thunk)
);
您只需将thunk添加到商店,如上所述

您可以通过如下方式重构代码,使其更加清晰

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将在开发和生产模式中更改,您可以使用以下方式:

在你的申请表的某个地方

 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返回的函数的第三个参数。第二个参数给出当前状态

 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())

如果要在动作创建者中编写异步代码,则需要编写异步动作创建者。常规操作创建者返回对象,而异步操作创建者返回函数而不是对象

export function testAction(data) {
   return async function(dispatch) {
      // async code
   }
}
在异步操作创建者返回的函数中,您可以访问
dispatch
,该函数可用于在服务器成功响应的情况下分派任何成功操作,并且在出现错误的情况下,您可以分派指示发生错误的操作

export function testAction(data) {
    return async function (dispatch) {
        try {
            let response = await axios.get(`https://jsonplaceholder.typicode.com/todos/1`);

            dispatch({
              type: 'TEST_ACTION',
              payload: response
            });

       } catch(err) {
           dispatch({type: 'TEST_ACTION_ERROR', message: 'error occurred'});
       }
   }
}
如果代码中有异步操作创建者,还需要使用中间件。此中间件允许操作创建者返回函数


有关如何创建异步操作创建者以及如何设置
redux-thunk
中间件以使异步创建者工作的完整详细信息,请查看您是否选中了
redux-thunk
?不要像那样返回动作创建者。通过
redux thunk
创建异步动作创建者,并在那里执行逻辑。谢谢!您如何将调度传递给动作创建者?类似于从'react redux'导入{useDispatch};const dispatch=usedpatch()感谢您的回复!这就把事情弄清楚了一点。您通常如何从组件调用这些操作?只需在需要时调用它们,然后监听状态更改并相应地采取行动(显示微调器、错误消息、结果)。您不调用动作创建者,而是像调度同步动作创建者一样调度它