Redux Saga如何解析数据

时间:2019-03-28 23:55:52

标签: generator redux-saga

您好,第一次使用发电机或Redux Sagas。我需要解析这些数据。我确定我做错了,因为它不起作用哈。我该如何工作?如果尝试通过某个函数将数据错误记录出来,否则可以通过控制台注销它。

我还必须写一些其他的东西才能使这篇文章通过..... yada yada。

import { takeEvery, take, call, put, all } from 'redux-saga/effects';
import axios from 'axios';

// 1. Worker Saga
export function* asyncAjax(){
    console.log("asyncAjax")
    const url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/",
          urlSuffix = [
            "all_hour.geojson",
            "all_day.geojson",
            "all_week.geojson",
            "all_month.geojson"
          ] 

    for (var i = 0; i < urlSuffix.length; i++) {

        yield console.log("for loop index: "+i)

        try {
            // AJAX geoJSON
            const response = yield call(axios.get, (url+urlSuffix[i])),
                  { features } = response.data

            parseData(features, i)


        } catch (e) {
            alert("Data Download Error")
            console.log(e)
        }

    }

    // yield put({ type: "VIZ_INIT_SUCCESS", action: true })

}

function parseData(features, i){
    let arr = []

    // Data Parsing
    for (let feature of features) {
        let magnitude = features.properties.mag,
            location = features.properties.place,
            time = features.properties.time,
            coordinates = features.geometry.coordinates,
            quake = {
                "magnitude": magnitude,
                "location": location,
                "time": time,
                "coordinates": coordinates
            }

        arr.push(quake)
    }

    console.log(arr)

    // Data Sorting by Highest Magnitude
    arr.sort((a, b) => {
        return b["magnitude"] - a["magnitude"]
    })

    console.log("quakes saga")
    console.log(arr)

    // Storing in State
    put({ 
        type: "QUAKES", 
        action: { 
            "index": i,
            "value": arr  
        } 
    })

    // Updating Progress Text/Bar
    put({ 
        type: "PRELOADER_TEXT", 
        action: {
            "payload": `Loading Data ${i}/4`
        } 
    })

    put({ 
        type: "PROGRESS_COMPLETE", 
        action: {
            "payload": (i/4)*100
        } 
    })
}



// 2. Watcher Saga
export function* watchAJAX(){
    console.log("redux-saga is executing AJAX")
    yield takeEvery('VIZ_INIT', asyncAjax)
}

// 3. Root Saga
export default function* rootSaga(){
    yield all([
        watchAJAX(),
    ])
};

1 个答案:

答案 0 :(得分:0)

parseData应该是一个生成器,当您打电话时应该像这样调用它 yield call(parseData, features, i) 并在parseData函数中确保使用yield yield put({...})