2016-10-02 5 views
17

나는 reactjs/redux의 초보자이며 API 호출을 사용하여 redux 앱에서 데이터를 검색하는 방법에 대한 간단한 예제를 찾을 수 없습니다. jquery ajax 호출을 사용할 수 있지만 거기에는 더 좋은 옵션이있을 것 같습니까?redux에서 API를 통해 데이터를 가져 오는 방법은 무엇입니까?

+0

https://github.com/argelius/react-onsenui-redux-weather/tree/master/api (HTTP [I 반응-REDUX에서 HTTP 요청을 어떻게해야합니까?]의 –

+0

가능한 중복 : //stackoverflow.com/questions/39794895/how-do-i-make-an-http-request-in-react-redux) –

답변

30

JSfiddle; http://jsfiddle.net/cdagli/b2uq8704/6/

redux, redux-thunk 및 fetch를 사용합니다.

가져 오기 방법;

(참고 :.. 당신은 예를 들어 fetchPostRequest는 로딩 표시기를 표시하는 데 사용할 수있는 많은 작업을 정의 할 수 아니면 다른 HTTP 상태 코드의 경우 다른 작업을 전달할 수 있습니다)

이상 사용

function fetchPostsWithRedux() { 
    return (dispatch) => { 
    dispatch(fetchPostsRequest()); 
    return fetchPosts().then(([response, json]) =>{ 
     if(response.status === 200){ 
     dispatch(fetchPostsSuccess(json)) 
     } 
     else{ 
     dispatch(fetchPostsError()) 
     } 
    }) 
    } 
} 

function fetchPosts() { 
    const URL = "https://jsonplaceholder.typicode.com/posts"; 
    return fetch(URL, { method: 'GET'}) 
    .then(response => Promise.all([response, response.json()])); 
} 

작업

function fetchPostsRequest(){ 
    return { 
    type: "FETCH_REQUEST" 
    } 
} 

function fetchPostsSuccess(payload) { 
    return { 
    type: "FETCH_SUCCESS", 
    payload 
    } 
} 

function fetchPostsError() { 
    return { 
    type: "FETCH_ERROR" 
    } 
} 

그리고 감속기에서 상태로 게시물을로드 할 수 있습니다.

연결 한 상태에서 구성 요소의 상태 및 동작에 액세스 할 수 있습니다.

connect(mapStateToProps, {fetchPostsWithRedux})(App); 
+0

고마워요 좋은 일 –

+0

이상한,이 정확한 코드를 사용하면 '잡히지 않습니다 (약속 있음) 오류 : 감속기가 작업을 발송하지 못할 수 있습니다.' – csilk

+0

무엇을합니까? 'Promise.all ([response, response.json()])'을 반환합니까? response.json()을 돌려주지 않는 이유는 무엇입니까? – Rohmer

5

API 요청을 수행 할 작업을 만듭니다. axios 또는 fetch와 같은 라이브러리를 사용하여 약속을 반환 할 수 있습니다.

감속기/reducer_something.js을 :

행동 /하는 index.js 다음과 같이 감속기에서 다음

import axios from 'axios'; 

export const FETCH_SOMETHING= 'FETCH_SOMETHING; 
const ROOT_URL = 'http://api.youapi.com'; 

export function fetchWeather(city) { 

    const url = `${ROOT_URL}&q=${aParamYouMayNeed}`; 
    const request = axios.get(url); 

    return { 
     type: FETCH_SOMETHING, 
     payload: request 
    }; 
} 

는 한 번에 해결 약속의 결과를 소비

코드 빌려

import { FETCH_SOMETHING} from '../actions/index'; 

export default function(state = [], action) { 
    switch (action.type) { 
     case FETCH_SOMETHING: 
     return [ action.payload.data, ...state ]; 
    } 

    return state; 
} 
Stephen Grider에서. 이것은 그의 레포입니다 : https://github.com/StephenGrider/ReduxCasts/tree/master/weather/src

+0

플 런커가 있습니까? –

+0

아니요, 테스트 한 myresponse (방금 편집 한)의 샘플을 복제 할 수 있으며 정상적으로 작동합니다. – Franco

+0

어떻게 감속기에서'.then()'을 사용하여 Promise가 완료되었고'data'가'undefined'가 아닌지 확인해야합니까? – jhuang

관련 문제