【问题标题】:Redux-saga how to pass parameters to request inside sagaRedux-saga 如何在 saga 内部向请求传递参数
【发布时间】:2020-07-03 03:21:08
【问题描述】:

我有一些代码需要更新。这不是我的代码,所以我不想要太多更改。它使用 redux-saga 和 axios。我想向 saga 传递一些参数

我在 sagas.js 中的传奇

export function* getInfoSaga() {
    while (true) {
        yield take(mutations.GET_INFO);
        const url1 = `${url}/api/getInfo/1-100`;
        const logInfo = yield axios.get<any>(url1).then(response => response);
        yield put(mutations.setInfo(logInfo.data.data));
    }
}

mutations.js

export const GET_INFO = 'GET_INFO';

export const getInfo = () => ({
    type: GET_INFO,
});

sagas 在 index.js

中运行
const s = sagas as any;

for (const saga in s) {
    sagaMiddleware.run(s[saga]);
}

在某些文件中,该操作由带有事件的按钮运行:

 onClick={() => dispatch({
                        type: 'GET_INFO',
                    })}

我想传递一些参数来修改请求 url,我尝试在 dipatch 请求中获取附加对象,并将参数添加到 sagas.js 和 mutatuions.js 中的生成器,但是我得到了一个错误 cannot access prperty of undefined

【问题讨论】:

    标签: javascript reactjs typescript react-redux redux-saga


    【解决方案1】:

    你试过了吗:

    onClick={() => dispatch({
      type: 'GET_INFO',
      url: 'your/url/goes/here'
    })}
    
    export function* getInfoSaga(action) {
        while (true) {
            yield take(mutations.GET_INFO);
            const url1 = `${action.url}/api/getInfo/1-100`;
            const logInfo = yield axios.get<any>(url1).then(response => response);
            yield put(mutations.setInfo(logInfo.data.data));
        }
    }
    
    

    【讨论】:

      【解决方案2】:

      更新:传递有效载荷并仅从 'take' 分配返回值

      onClick={() => dispatch({
        type: 'GET_INFO',
        payload: {
          key1: value1
          // other values here
        }
      })}
      
      export function* getInfoSaga() {
         const action = yield take(mutations.GET_INFO);
         // action.payload.key1
      }
      

      【讨论】:

      • 我正在使用 TypeSript 并出现错误:TypeError: Cannot destructure property 'payload' of 'undefined' as it is undefined. With:export function* getInfoSaga({ payload } : { payload : IPayload}) { any 类型也是如此
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 2019-06-05
      • 2019-12-09
      • 2018-04-23
      • 2018-03-16
      • 2018-08-04
      相关资源
      最近更新 更多