2016-12-27 6 views
0

redux-thunkaxios .Iは`redux-thunk`を使って反応するときにajaxを呼び出す方法は?

簡単な方法

axios.get('data.json').then((data)=>{ 
     console.log(data); 
    }) 

(このようなボタンのクリックコールで)JSONファイルからデータを取得したい使用して反応に私は、コールAJAXをしようとしています。しかし、私が使用したいですredux-thunk。言い換えれば、私は使用するコンポーネントで購読する必要がありますthunk

ここではサンクを使用できますか?ここ は私のコードは、あなたがそれをチェックアウトする場合があります...この程度egghead.ioの良いチュートリアルはあり https://plnkr.co/edit/bcGI7cHjWVtlaMBil3kj?p=preview

const thunk = ReduxThunk.default; 
const abc= (state={},action) => { 
    console.log('in redux', action.type) 
    switch(action.type){ 
    case 'GET_DATA': 
     return dispatch =>{ 
     return axios.get('data.json'); 
     }; 

     default : 
     return state; 
    } 
} 
const {createStore,bindActionCreators ,applyMiddleware } =Redux; 
const {Provider,connect} =ReactRedux; 

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

class First extends React.Component { 
    constructor (props){ 
    super(props); 

    } 

    getDate(){ 
    this.props.getData(); 
    // axios.get('data.json').then((data)=>{ 
    // console.log(data); 
    // }) 
    } 
    render(){ 
    return (
    <div> 
     <button onClick={this.getDate.bind(this)}>GET DATA</button> 

    </div> 
    ) 
    } 
} 

const actions = { 
    getData:() => { 
     return { 
      type: 'GET_DATA', 
     } 
    } 
}; 

const AppContainer = connect(
    function mapStateToProps(state) { 
     return { 
      digit: state 
     }; 
    }, 
    function mapDispatchToProps(dispatch) { 
     return bindActionCreators(actions, dispatch); 
    } 
)(First); 
ReactDOM.render(
    <Provider store={store}> 
    <AppContainer/> 
    </Provider> 
    ,document.getElementById('root')) 

答えて

1

私はAPIを呼び出すために、ここで例としてaxiosを使用している、あなたのような何かを試すことができfetchまたはsuperagent also.Youを使用することができます。

AXIOS

axios.get('//url') 
    .then(function (response) { 
    //dispatch action 
    }) 
    .catch(function (error) { 
    // throw error 
    }); 

だから、今の状態に来て、API呼び出しのためでした。 reduxにはあなたのアプリを扱う1つの状態があります。私はあなたがhere見つけることができるreduxの基本を通過することをお勧めします。だから、あなたのAPI呼び出しが成功すると、あなたの状態をデータで更新する必要があります。状態

function receiveData(data) { 
     return{ 
     type: 'RECEIVE_DATA', 
     data 
    } 
    } 

減速

function app(state = {},action) { 
     switch(action.types){ 
      case 'RECEIVE_DATA': 
       Object.assign({},...state,{ 
        action.data 
        } 
        }) 
      default: 
      return state 
     } 
    } 
を更新する

function fetchData(){ 
    return(dispatch,getState) =>{ //using redux-thunk here... do check it out 
     const url = '//you url' 
     fetch(url) 
     .then (response) => {dispatch(receiveData(response.data)} //data being your api response object/array 
     .catch(error) => {//throw error} 
    } 
    } 

アクションデータをフェッチする

アクション

関連する問題