来自redux-saga的Saga被忽略,只使用了reducer

时间:2017-10-25 15:57:10

标签: javascript reactjs redux redux-saga saga

此处遇到redux-saga问题。我打电话给toggleSidebar()打开/关闭侧边栏。然而,这是有效的,传奇被忽略了。我使用console.logreducer中的saga登录到控制台,但只有reducer日志登录到控制台。

边栏打开/关闭,但为什么传奇被忽略?

  

/sagas/templateSaga.js - 不登录控制台

import { FETCH_DEFAULT_TEMPLATE, RECEIVE_DEFAULT_TEMPLATE } from '../actions'

function* toggleSidebar(action) {
  console.log("Called toggleSidebar in Saga")
  yield put({type: 'TOGGLE_SIDEBAR', data: action.payload});
}


export default function* templateSaga() {
  yield takeLatest("TOGGLE_SIDEBAR", toggleSidebar);
}
  

/reducers/templateReducer.js - 登录控制台

export default (state = initialState, {type, data = ""}) => {
  switch (type) {
    case TOGGLE_SIDEBAR: {
      console.log("Called toggleSidebar in reducer");
      return {...state, collapsed: data}
    }
    default: {
      return {
        ...state
      }
    }
  }
}
  

/actions/index.js

export const TOGGLE_SIDEBAR = 'TOGGLE_SIDEBAR'
export const toggleSidebar = data => ({type: TOGGLE_SIDEBAR, data})
  

/reducers/index.js(rootReducer)

import templateReducer  from './templateReducer'

export default combineReducers({
  templateReducer
})
  

/sagas/index.js(rootSaga)

import templateSaga from './templateSaga'

export default function* rootSaga() {
  yield all([
    ...templateSaga
  ])
}

我的商店配置如下:

import createSagaMiddleware                      from 'redux-saga'
import rootReducer     from '../modules/reducers'
import rootSaga from '../modules/sagas'

const sagaMiddleware    = createSagaMiddleware(rootSaga);

const middleware = [
  sagaMiddleware,
  routerMiddleware(history)
]

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

最后,在我的App中我正在使用:

const mapStateToProps = state => ({
  template: state.templateReducer
})
const mapDispatchToProps = dispatch =>
    bindActionCreators({ toggleSidebar }, dispatch)


export default connect(mapStateToProps, mapDispatchToProps)(App);

1 个答案:

答案 0 :(得分:1)

错误可能在/sagas/index.js(rootSaga) 尝试将...templateSaga更改为fork(templateSaga),如下所示:

import { fork } from 'redux-saga/effects'
import { templateSaga } from './templateSaga'

export default function* rootSaga() {
  yield all([
    fork(templateSaga)
  ])
}

export default function* templateSaga更改为

export function* templateSaga() {
  yield takeLatest("TOGGLE_SIDEBAR", toggleSidebar);
}

此外,您在/sagas/templateSaga.js中有某种循环,您可以在其中'TOGGLE_SIDEBAR'并立即发送相同的类型