1

React-sagaでリクエストからjsonを取得したい!私のサガが生成するデータをどのように取得するのか疑問に思っていました.takeLatestで「REQUEST_DONE」アクションを監視し、再レンダリングするcomponentWillMountでジェネレーター関数を呼び出すという考えがあります。

しかし、コンポーネントの 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() { ... }
4

1 に答える 1

3

webpackbin DEMO を編集

fetch を呼び出して結果を生成する

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);
于 2016-07-27T17:11:52.173 に答える