使用 Redux Saga 显示 HTTP 请求响应

Displaying HTTP Request Reponse With Redux Saga

嘿,所以我想从带有 react-saga 的请求中得到一个 json!我想知道我将如何获得我的传奇产生的数据,我有一个想法在 componentWillMount 中调用一个生成器函数,该函数使用 takeLatest 监视 'REQUEST_DONE' 操作,然后重新渲染。

但我认为在我的一个组件中使用 react-saga 是个坏主意。请指导

我的 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() { ... }

编辑 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);