2016-12-01 17 views
0

Redux 사용법을 배우고 있습니다. 단 하나의 버튼으로 간단한 애플리케이션을 만들고 싶습니다. 버튼을 클릭하면 나머지 API 호출을 원하고 응답이 돌아 오면 응답 내용을 표시해야합니다.react + redux로 전화 해주세요

사용자가 버튼을 클릭하면 store.dispatch(CardAction.GET_CARDS) 메시지를 Redux로 보냅니다. 버튼의 onClick 핸들러에서 직접 나머지 api를 호출하고 싶지는 않습니다.

답변을 받으려면 store.dispatch(CardAction.UPDATE_UI)과 함께 이벤트를 보내고 어떻게 든 백그라운드에서 Redux의 상태를 업데이트하고 싶습니다.

이 개념이 React + Redux와 맞기를 희망합니다.

일부 JavaScript 코드가 완료되었지만 일부 코드가 누락되었습니다. 부품을 모으는 것을 도와 주시겠습니까?

index.jsp를

<!DOCTYPE html> 
<%@page session="false"%> 
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> 

<html> 
    <head> 
     <meta http-equiv="CONTENT-TYPE" content="text/html; charset=UTF-8"> 
     <base href="${pageContext.request.contextPath}/" /> 
     <link rel="icon" type="image/x-icon" href="public/image/favicon.ico"> 
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"> 
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css"> 
    </head> 
    <body> 
     <div id="root"></div> 
     <script type="text/javascript" src="bundle.js"></script> 
    </body> 
</html> 

App.js

let store = createStore(reducers); 

ReactDom.render(
    <Provider store={store}> 
     <Card/> 
    </Provider>, 
    document.getElementById('root') 
); 

Card.js

export default class Card extends React.Component { 
    render() { 
     return (
      <div> 
       ... 
       <Button onClick={() => store.dispatch(CardAction.GET_CARDS)}>rest call</Button> 
      </div> 
     ) 
    } 
} 

ActionType.js

export const GET_CARDS = 'get-cards'; 
export const UPDATE_UI = 'update-ui'; 

CardAction.js

export function getCards(param1, param2) { 
    return createAction(ActionType.GET_CARDS, (param1, param2) => ({ value1, value2 })) 
} 

export function updateUi() { 
    return createAction(ActionType.UPDATE_UI) 
} 

RootReducer.js

export const reducers = (state = {}, action) => { 
    return action 
}; 

RestClient.js

,
export default { 
    cardPost(param1, param2) { 
     const url = ...; 

     fetch(url, { 
      method: 'POST', 
      credentials: 'include' 
     }) 
      .then(response => { 
       if (response.ok) { 
        console.info('rest response have arrived'); 
        store.dispatch(CardAction.UPDATE_UI) 
       } else { 
        console.info('error appeared during calling rest api'); 
        //store.dispatch(CardAction.SHOW_ERROR) 
       } 
      }) 
      .catch(function(err) { 
       console.info(err + ' Url: ' + url) 
      }) 
    } 
} 
+0

는 "createAction는"당신의 사용자 정의 함수 할 거라고? –

+0

그것은 'redux-actions'의 import {createAction}에서 가져옵니다. – zappee

답변

1

구성 요소에서 store.dispatch()를 호출하면 안됩니다. 대신, 이전에 작성한 작업을 가져와야하고 나머지는 나머지 항목을 수행해야합니다. 감속기는 액션을 반환하지 말고 이전 상태를 음소거하지 않고 새 상태를 반환해야합니다. 내가 먼저 REDUX 경험의 이해 부족의 일부를 수정해야 좋을 것, 그리고 당신은이 것과 같은 반작용-돌아 오는 받침대 튜토리얼을 따라하기 위해 시도 할 수 있습니다 : https://medium.com/@rajaraodv/a-guide-for-building-a-react-redux-crud-app-7fe0b8943d0f#.cnat3gbcx이 가

가 [편집] 가 여기에 무엇을의

I

// component Card.js 
 
import {getCards} from "CardAction"; 
 

 
export default class Card extends React.Component { 
 
    render() { 
 
     return (
 
      <div> 
 
       ... 
 
       <Button onClick={getCards(param1, param2)}>rest call</Button> 
 
      </div> 
 
     ) 
 
    } 
 
} 
 

 
// action CardAction.js 
 
const receivedCards = (cards) => ({ 
 
\t type: "RECEIVED_CARDS", 
 
\t cards 
 
}) 
 

 
export function getCards(param1, param2) { 
 
    // idk where you're gonna use these params btw 
 
    // also please note that fetch() isn't supported by older browsers. Here I'm showing you a simple example with axios, which basically performs the same operation. Feel free to adapt this example code as you want. 
 
\t return function(dispatch) { 
 
\t \t return axios({ 
 
\t \t \t url: server + "endpoint", 
 
\t \t \t timeout: 20000, 
 
\t \t \t method: 'get' 
 
\t \t }) 
 
\t \t .then(function(response) { 
 
\t \t \t let cards = response.data; 
 
\t \t \t dispatch(receivedCards(cards)); 
 
\t \t }) 
 
\t \t .catch(function(response){ 
 
\t \t \t console.log(response.data.error); 
 
\t \t }) 
 
\t } 
 
}; 
 

 
// reducer reducer.js 
 
const initialState = {}; 
 
export default (state = initialState, action) => { 
 
    switch(action.type) { 
 
    case "RECEIVED_CARDS": 
 
     return Object.assign({}, 
 
     state, 
 
     {cards: action.cards}); 
 
    default: 
 
     return state; 
 
    } 
 
}

+0

이렇게하면 뭔가를해야합니까? store.dispatch() 코드를 어디에 넣을 수 있습니까? – zappee

+1

내 편집을 참조하십시오 –

+0

도와 주셔서 감사합니다.나머지 콜백 부분을 제외하고 코드가 제대로 작동합니다. 이 오류가 발생합니다 : TypeError : 디스패치는 함수가 아닙니다. 디스패치 (...) 대신 this.props.dispatch (...)를 사용하면 오류는 TypeError : 이것은 정의되지 않습니다. .then ((response) => {this.props.dispatch (...)}가 사용되면 오류는 TypeError : _this가 null입니다. 도와 주시겠습니까? – zappee

관련 문제