【问题标题】:how to get redux state inside saga file如何在 saga 文件中获取 redux 状态
【发布时间】:2021-12-21 10:19:07
【问题描述】:

我需要从 redux 获取状态,以便在 saga 文件中的 API 调用中使用它。
我检查了选择 API。但这是一个问题。
我想将一个函数仅用于 API 调用。要运行这个函数,我需要从 redux 获取当前状态。而不是把它放在生成器函数中,我没有成功使用选择。

    async function getApi(){
// GET THE STATE IN THE NEXT LINE
        try{
            const callByCity = await fetch(`https://www.test.com/APICALL${REDUX STATE}...
`)
            const result= await callByCity.json()
            return result
        } catch(error) {
            console.log(error.message)
        }
    }
    
    function* fetchMainCity(action){
      try{
        const mainCity = yield call(getApi);
        yield put({ type: "GET_CITY_SUCCESS", result: result})
      } catch (e) {
        yield put({type: "GET_CITY_FAILED", message: "Sorry, We Have A Problem."})
      }
    }

【问题讨论】:

标签: reactjs redux redux-saga


【解决方案1】:

顺便说一句,你也可以在你的 redux 状态下获得一个字段
假设你的 redux 状态是这样的

{ key1: val1 , key2:{}}

你可以 const key1 = yield select(state => state.key1).
因为通常你不想选择整个 redux 状态

【讨论】:

  • 酷!非常感谢!
【解决方案2】:

你有一个传奇和一个async 函数的混合体。您可以在传奇中获得状态。您无法在 async 函数中获取它。所以如果你想让getApi作为一个异步函数,你需要先获取状态,然后传入:

function* fetchMainCity(action) {
  try {
    const state = yield select();
    const mainCity = yield call(getApi, state);
    //...etc
}

async function getApi(state) {
  // do stuff with the state
}

或者,如果您将getApi 更改为saga,那么它可以从状态本身中进行选择:

function* getApi() {
  try {
    const state = yield select();
    const callByCity = yield fetch(`https://www.test.com/APICALL${/* state stuff */}`);
    const result = yield callByCity.json();
    return result;
  } catch (error) {
    console.log(error.message);
  }
}

【讨论】:

  • 知道了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2017-09-14
  • 2021-07-31
  • 2021-03-13
  • 2021-08-17
  • 2016-10-12
  • 2021-02-20
  • 1970-01-01
  • 2017-11-28
相关资源
最近更新 更多