簡體   English   中英

使用 redux saga 獲取數據

[英]Fetch data with redux saga

我創建了一個示例,用於從使用redux-thunk API 獲取數據。 以下代碼正在運行。

在這種情況下,我想重寫我的代碼,但使用redux saga

 import React from 'react'; import {createStore, applyMiddleware} from 'redux'; import ReactDOM from "react-dom"; import thunk from 'redux-thunk'; import axios from 'axios'; function App(props) { const initialState = { loading: false, data: [], error: '' }; const reducer = function (state = initialState, action) { switch (action.type) { case 'START_FETCH': return { ...state, loading: true }; case 'PROCESS_FETCH': return { ...state, loading: false, data: action.payload, error: "" }; case 'END_FETCH': return { ...state, loading: false, data: [], error: action.payload } } return state; }; const START_FETCH = 'START_FETCH'; const PROCESS_FETCH = 'PROCESS_FETCH'; const END_FETCH = 'END_FETCH'; let startFetchFun = () => { return { type: START_FETCH, loading: true } }; let processFetchFun = (users) => { return { type: PROCESS_FETCH, payload: users } }; let endFetchFun = (error) => { return { type: PROCESS_FETCH, payload: error } }; let fetchUsersWithThunk = () => { return function (dispatch) { dispatch(startFetchFun()); axios.get('https://jsonplaceholder.typicode.com/users') .then((response) => { dispatch(processFetchFun(response.data)); }) .catch((error) => { dispatch(endFetchFun(error.message)); console.log(error.message); }) } }; const store = createStore(reducer, applyMiddleware(thunk)); store.subscribe(() => { console.log(store.getState()) }); store.dispatch(fetchUsersWithThunk()); return ( <div className="main"> <h1>Redux-Thunk</h1> </div> ); } ReactDOM.render( <App/>, document.getElementById('root'));

我想使用 redux saga 編寫上面的代碼,以更好地理解 saga。 那么,如何在這個例子中使用 redux-saga 呢? 誰能幫助我?

Redux Saga 使用yield call像 API 服務一樣調用 promise,並使用yield put將操作分派到 store。

區別在於阻塞和不阻塞調用。 因為我們想等待服務器響應我們的請求,所以我們將使用作為阻塞函數的yield call 使用yield put({ type: "actionName" })代替直接在 generator saga 內分派動作。 這對於測試目的也很有用。

所以你應該寫你的傳奇如下:

import {all, fork, put, call, takeLatest} from 'redux-saga/effects';

function* handleRequest (action) {
  try {
    yield put(startFetchFunc()); // dispatch the action to the store.
    const result = yiels call(apiService.users, [data to pass]); // wait for the response blocking the code execution.
    yield put(processFetchFun(result)); // dispatch the action to the store containing  the data
   } catch (e) {
    yield put(endFetchFun('Error'));
   }
}

function* watchRequest() {
   yield takeLatest({type: "START_FETCH"}, handleRequest);
}

export function* rootSaga() {
  yield all([
    fork(wathcRequest),
    // ... more watchers will be here...
  ]);
}

按照此處的說明配置您的存儲https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html

我建議您不止一次閱讀文檔。 它包含許多有用的信息,起初可能會很奇怪,但一旦您了解它的工作原理,就會清楚得多。

您需要配置您的商店以使用 saga 中間件:

import React from 'react';
import createSagaMiddleware from 'redux-saga';
import { createStore, applyMiddleware } from 'redux';
import reducer from './reducers';
import rootSaga from './sagas';
const sagaMiddleware = createSagaMiddleware();

const store = createStore(
   reducer,
   applyMiddleware(sagaMiddleware, logger),
);
sagaMiddleware.run(rootSaga); // < -- rootSaga exports all sagas in your app

然后你可以將你的 thunk 轉換為一個 saga:

import {call} from 'redux-saga/effects';

function* fetchUsersSaga(payload){
    try {
        yield call(startFetchFun());
        axios.get('https://jsonplaceholder.typicode.com/users')
        .then((response) => {
            yield call(processFetchFun(response.data));
        })
    } catch(err) {
        yield call(endFetchFun(error.message));
        console.log(error.message);
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM