如何在 saga 文件中获取 redux 状态

how to get redux state inside saga file

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

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

您混合了 saga 和 async 函数。您可以在 saga 中获取状态。在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 更改为传奇,那么它可以 select 来自状态本身:

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

顺便说一下,你也可以在你的 redux 状态中得到一个字段
假设你的 redux 状态看起来像这样

{ key1: val1 , key2:{}}

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