2017-01-10 3 views
4

저는 썽크를보고 API 호출을 구현하는 방법을 찾으려고합니다. 그것은 작동하지 않기 때문에 나는 아주 기초로 돌아갔다. 버튼을 클릭하면 콘솔에 'Getting here!이 표시되지만, console.log(dispatch) 일 때 아무 것도 표시되지 않습니다. 내가 여기서 뭔가를 놓치고 있니?Redux-thunk 디스패치가 작동하지 않습니다.

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import { createStore, applyMiddleware } from 'redux'; 
import { connect, Provider } from 'react-redux'; 
import thunk from 'redux-thunk' 
import axios from 'axis'; 

const store = createStore(
    reducer, 
    applyMiddleware(thunk) 
); 

function fetchUser() { 
    return axios.get('https://randomuser.me/api/'); 
} 

function addUser() { 
    console.log('Getting here'); 
    return (dispatch) => { 
     console.log(dispatch) //not showing anything 
     return fetchUser().then(function(data){ 
      console.log(data); 
     }); 
    }; 
} 

class App extends React.Component { 
    addUser() { 
     addUser(); 
    } 

    render() { 
     return (
      <button onClick={this.addUser.bind(this)}>+</button> 
     )  
    } 
} 

const mapPropsToState = function(store){ 
    return { 
     newState: store 
    } 
} 

var ConnectApp = connect(mapPropsToState)(App); 

ReactDOM.render(
    <Provider store={store}> 
     <ConnectApp /> 
    </Provider>, 
    document.getElementById('app') 
) 
+0

@lux이 –

+1

지도를 확인하십시오 .DispatchToProps in redux –

답변

7

구성 요소에서 일반 기능으로 addUser()을 호출 할 수 없습니다. addUser()을 파견하려면 mapDispatchToProps 함수를 사용하고 connect 호출에 전달해야합니다.

const mapDispatchToProps = dispatch => ({addUser:() => dispatch(addUser())}) 

ConnectApp = connect(mapPropsToState, mapDispatchToProps)(App); 

이제 소품으로 호출 할 수 있습니다.

addUser() { 
     this.props.addUser(); 
    } 
2

실제로 썽크를 파견하는 것은 아닙니다. 당신은 직접 그것을 부르고 있습니다. 내부 () => {} 썽크 함수를 dispatch에 전달해야합니다.

처리 방법에는 여러 가지가 있습니다. mapDispatchToProps 인수를 connect에 제공하지 않으므로 App 구성 요소에 자동으로 this.props.dispatch()이 제공됩니다. 따라서 App.addUser()에서 this.props.dispatch(addUser())을 할 수 있습니다.

또 다른 방법은 액션 생성자 addUser을 사전 바인딩하는 것입니다. 구문 var ConnectApp = connect(mapPropsToState, {addUser})(App)으로이 작업을 수행 할 수 있습니다. 그런 다음 this.props.addUser()으로 전화하면 결과가 자동으로 발송됩니다.

내가 어떤 행동 제작자의 사용에 대한 토론과 http://blog.isquaredsoftware.com/2016/10/idiomatic-redux-why-use-action-creators/에 바인딩 및 바인딩 및 https://gist.github.com/markerikson/6c7608eee5d2421966d3df5edbb8f05chttps://gist.github.com/markerikson/f46688603e3842af0f9720dea05b1a9e에 파견을위한 샘플 코드와 몇 기 스트 있습니다.

+0

thanks @ markerikson. 나는 지금 이것들을 읽을 것이다. –