2016-07-27 82 views
1

Heyy所以我想從請求中得到一個json,帶有react-saga!我想知道如何獲得數據,我的傳奇產量,我有一個想法,在componentWillMount中調用generator函數,用takeLatest監視'REQUEST_DONE'動作,然後重新渲染。用Redux Saga顯示HTTP請求響應

但我認爲在我的一個組件中使用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

編輯webpackbin 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);