2017-10-04 9 views
0

저는 2 주 동안 React Native으로 공부하고 있습니다. ReduxRedux-Sagas으로 작업하고 있습니다. 나는 이것을 며칠 동안 연구하려고 노력했다. (생각한) 나는 그것에 매달려 있었다. 그러나 불행하게도 나는 아직도 고심하고있다. 여기에 내가 읽고 시도 일부 리소스는 다음과 같습니다디스플레이 반응 기본 Redux Saga API 응답

https://shift.infinite.red/using-redux-saga-to-simplify-your-growing-react-native-codebase-2b8036f650de

https://hackernoon.com/moving-api-requests-to-redux-saga-21780f49cbc8

나는 날씨 데이터에 대한 API를 쿼리 응용 프로그램을 만들 수 Ignite-CLI 보일러를 사용하고 있습니다. API 요청은 api.get() 일반 apisauce의 함수를 사용할 때 작동하지만 데이터를 반환하는 Redux Saga 액션을 얻을 수 없습니다. 나는 단지 개념을 충분히 이해하지 못한다고 생각하고있다. 여기

// a library to wrap and simplify api calls 
import apisauce from 'apisauce' 

// our "constructor" 
const create = (baseURL = 'https://my-api-url.com/api/') => { 

    const apiId = 'xxxxxxx' 
    const apiKey = 'xxxxxxxxxxxxxxxxx' 
    const resortKey = 'xxxxxx' 
    const apiParams = resortKey + '?app_id=' + apiId + '&app_key=' + apiKey 

    const api = apisauce.create({ 
    // base URL is read from the "constructor" 
    baseURL, 
    // here are some default headers 
    headers: { 
     'Cache-Control': 'no-cache' 
    }, 
    // 10 second timeout... 
    timeout: 10000 
    }) 

    const getReport =() => api.get(apiParams) 

    return { 
    getReport, 
    } 
} 

// let's return back our create method as the default. 
export default { 
    create 
} 

의 Ignite CLI가 가지고있는 지정된 파라미터에서 JSON 데이터 (이 완벽하게 작동)

/App/Services/Api.js를 가져 apisauce를 사용하여 내 Api.js 파일입니다 자동으로 감속적 인 행동과 무용담을 생성하는 멋진 생성기. 다음은 그 생성 된 파일은 다음과 같습니다

/App/Redux/SnowReportRedux.js (돌아 오는 작업)

import { createReducer, createActions } from 'reduxsauce' 
import Immutable from 'seamless-immutable' 

/* ------------- Types and Action Creators ------------- */ 

const { Types, Creators } = createActions({ 
    snowReportRequest: ['data'], 
    snowReportSuccess: ['payload'], 
    snowReportFailure: null 
}) 

export const SnowReportTypes = Types 
export default Creators 

/* ------------- Initial State ------------- */ 

export const INITIAL_STATE = Immutable({ 
    data: null, 
    fetching: null, 
    payload: null, 
    error: null 
}) 

/* ------------- Reducers ------------- */ 

// request the data from an api 
export const request = (state, { data }) => 
    state.merge({ fetching: true, data, payload: null }) 

// successful api lookup 
export const success = (state, action) => { 
    const { payload } = action 
    return state.merge({ fetching: false, error: null, payload }) 
} 

// Something went wrong somewhere. 
export const failure = state => 
    state.merge({ fetching: false, error: true, payload: null }) 

/* ------------- Hookup Reducers To Types ------------- */ 

export const reducer = createReducer(INITIAL_STATE, { 
    [Types.SNOW_REPORT_REQUEST]: request, 
    [Types.SNOW_REPORT_SUCCESS]: success, 
    [Types.SNOW_REPORT_FAILURE]: failure 
}) 

/App/Sagas/SnowReportSagas.js

import { call, put } from 'redux-saga/effects' 
import SnowReportActions from '../Redux/SnowReportRedux' 

export function * getSnowReport (api, action) { 
    const { data } = action 
    // make the call to the api 
    const response = yield call(api.getReport, data) 

    // success? 
    if (response.ok) { 
    yield put(SnowReportActions.snowReportSuccess(response.data)) 
    } else { 
    yield put(SnowReportActions.snowReportFailure()) 
    } 
} 

그런 다음, 그들이 제공 한 예제에 따라 SnowReportRedux.jsgetSnowReport에서 SnowReportSagas.js의 기능을 추가했습니다. t 사가 기능은 다음과 같습니다.

//...imports & constants 

export default function * root() { 
    yield all([ 
    // some sagas only receive an action 
    takeLatest(StartupTypes.STARTUP, startup), 

    // some sagas receive extra parameters in addition to an action 
    takeLatest(SnowReportTypes.SNOW_REPORT_REQUEST, getSnowReport, api) 
    ]) 
} 

여기 내가 혼란스러워합니다. 구성 요소 또는 화면 내에서 실제로 이러한 발송 작업을 호출하려면 어떻게해야합니까? 나는 import SnowReport Actions from '../Redux/SnowReportReduxmapDispatchToProps을 가지고 이해하지만 ... 여기 내 화면 중 하나에서 일부 조각입니다 화재로 파견을 얻을 수 없습니다

/App/Containers/ResortReportScreen.js이

//.. constructor 

componentDidMount() { 
    this.props.getSnowReport(); 
} 

// .. render()/close component 

const mapDispatchToProps = (dispatch) => { 
    return { 
    getSnowReport:() => dispatch({ type: SnowReportActions.snowReportRequest() }) 
    } 
} 

export default connect(null, mapDispatchToProps)(ResortReportScreen) 

componentDidMount() 기능이 작동하면 dispatchSnowReportActions.snowReportRequest() 동작을 수행해야합니까? 해당 동작의 응답을 반환하기 위해 console.log()을 사용할 때마다 발사는 끝나지 않습니다. 여기서 내가 뭘 잘못하고 있니? actions을 사용할 때 내 API 요청에서 데이터를 표시하려면 어떻게해야합니까?

sagaMiddlewarereducers은 모두 Ignite에서 자동으로 생성됩니다. 그것들을 보여줄 필요가 있다면 그냥 물어보십시오.

+0

체크 아웃 [여기] 내 환매 특약 (https를위한 방법의 객체를 사용하여 코드를 단순화 할 수

const mapDispatchToProps = (dispatch) => { return { getSnowReport:() => dispatch(SnowReportActions.snowReportRequest()) } } 

: // github.com/pritishvaidya/create-react-native-redux-app)를 예제와 함께 사용하십시오. –

답변

0

기능 SnowReportActions.snowReportRequest()은 발송해야하는 작업을 반환하는 작업 작성자입니다.당신은 그런 식으로 코드를 수정할 수 있습니다 : 심지어 대신 mapDispatchToProps (https://github.com/reactjs/react-redux/blob/master/docs/api.md)

const mapDispatchToProps = { 
    getSnowReport: SnowReportActions.snowReportRequest 
}