2016-07-27 19 views
1

私はreact-sagaでリクエストからjsonを取得したいと思っています!私は私の佐賀がもたらすデータをどのように得るのだろうと思っていましたが、takeLatestを使って 'REQUEST_DONE'アクションを監視してからrerendersを監視するcomponentWillMountでジェネレータ関数を呼び出すアイデアがあります。Redux SagaでHTTPリクエスト応答を表示

しかし、私は自分のコンポーネントの1つにreact-sagaを使用することをお勧めします。指導してください

マイサガファイル:

export function* Saga() { 
    yield fetch(url, { 
    method: 'GET', 
    headers: { 
     'Accept': '...', 
     'Content-Type': 'application/json' 
    } 
    }) 
    .then(response => { 
    return response.json(); 
    }) 
    .then(json => { 
    return json; 
    }) 
    .catch(ex => { 
    console.log('parsing failed', ex) 
    }) 
} 

export default function* watchAsync() { 
    console.log(yield Saga().next().value); // gets the value correctly 
    yield* takeLatest('BLAH', Saga); 
} 

マイコンポーネント

... 
componentWillMount() { 
    const { store } = this.context; 
    store.dispatch({type: 'BLAH'}); 
    // I want the request data 
    } 

    render() { ... } 

答えて

2

EDITwebpackbin DEMO

コールフェッチや歩留まり結果

import { take, put, call } from 'redux-saga/effects'; 

function fetchData() { 
    return fetch(url) 
    .then(res => res.json()) 
    .then(data => ({ data })) 
    .catch(ex => { 
     console.log('parsing failed', ex); 
     return ({ ex }); 
    }); 
} 

function* yourSaga(action) { 
    const { data, ex } = yield call(fetchData); 
    if (data) 
    yield put({ type: 'REQUEST_DONE', data }); 
    else 
    yield put({ type: 'REQUEST_FAILED', ex }); 
} 
export default function* watchAsync() { 
    yield* takeLatest('BLAH', yourSaga); 
} 

次にコンポーネントとスライスに必要なデータを接続する

class App extends Component { 
    ... 
    componentWillMount() { 
     this.props.dispatch({type: 'BLAH'}); 
    } 

    render(){ 
     return (<div>Data: {this.props.data}</div>); 
    } 
} 

export default connect(state =>({ 
    data:state.data 
}))(App); 
関連する問題