我使用this示例中的API调用使用react-redux和redux-saga。我的目标是使用不同的URL进行另一个API调用,并在不同的页面中使用它们。如何实现呢?

Sagas:

import { take, put,call } from 'redux-saga/effects';
import { takeEvery, delay ,takeLatest} from 'redux-saga';
function fetchData() {
    return  fetch("https://api.github.com/repos/vmg/redcarpet/issues?state=closed")
    .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);
}
export default function* rootSaga() {
    yield [
        watchAsync()
    ]
}

应用程序:
import React, { Component } from 'react';
import { connect } from 'react-redux';
class App extends Component {
    componentWillMount() {
        this.props.dispatch({type: 'BLAH'});
    }
    render(){
       return (<div>
            {this.props.exception && <span>exception: {this.props.exception}</span>}
            Data: {this.props.data.map(e=><div key={e.id}>{e.url}</div>)}

          </div>);
    }
}
export default connect( state =>({
    data:state.data , exception:state.exception
}))(App);

我的目标是做出另一个传奇,将在另一个组件中使用它,并且两者都不要互相混淆。那有可能吗?

最佳答案

当然,这就是Sagas的重点。

一个典型的应用程序将在后台等待多个sagas,等待一个或多个特定 Action (take效果)。

以下是如何从redux-saga issue#276设置多个sagas的示例:
./saga.js

function* rootSaga () {
    yield [
        fork(saga1), // saga1 can also yield [ fork(actionOne), fork(actionTwo) ]
        fork(saga2),
    ];
}
./main.js
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'

import rootReducer from './reducers'
import rootSaga from './sagas'


const sagaMiddleware = createSagaMiddleware()
const store = createStore(
  rootReducer,
  applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(rootSaga)

09-10 23:07