【问题标题】:Redux Sagas - dispatch undefinedRedux Sagas - 调度未定义
【发布时间】:2018-10-03 10:47:32
【问题描述】:

我是 redux-sagas 的新手,我仍在努力了解它们的工作原理。我正在尝试将 redux-saga 函数绑定到我的一个组件,该组件发出 API 请求,然后使用响应中的数据分派一个动作。尝试根据文档将调度传递给我的传奇函数参数时,我收到调度错误未定义。这是我的设置:

缩略图容器

import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getThumbnails } from '../../../containers/search/sagas';
import createReducer from './reducers';

class ThumbnailsContainer extends PureComponent {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
    this.props.getThumbnails()
  }

  render() {
    return (
      <div>My Container</div>
    )
  }
}

function mapDispatchToProps(dispatch) {
  return {
    getThumbnails: bindActionCreators(getThumbnails, dispatch)
  }
}


export default connect(null, mapDispatchToProps)(ThumbnailsContainer);

Sagas.js

export function* getThumbnails(dispatch) {

  console.log(dispatch)

  yield fetch('myAPIurl', {
    method: 'post',
    headers: {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/json'
    },
    body: {}
  }).then(res=>res.json())
    .then(res => {
      console.log(JSON.parse(res.data))
    });
}

rootsagas.js

import { all, fork } from 'redux-saga/effects';

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

Stores.js

import { applyMiddleware, compose, createStore } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootSaga from './rootsagas';

const sagaMiddleware = createSagaMiddleware();
const apolloMiddleware = apolloClient.middleware();

export default function configureStore(initialState = {}, history) {
  const middlewares = [
    sagaMiddleware
  ];
})

store.runSaga = sagaMiddleware.run(rootSaga);
store.asyncReducers = {}; // Async reducer registry

const store = createStore(createReducer(), applyMiddleware(...middlewares));

store.runSaga = sagaMiddleware.run(rootSaga);
store.asyncReducers = {}; // Async reducer registry

return store;

我想做的是在我得到 API 响应后调度一个动作,但似乎无法获得调度函数。在他们的文档中看不到我哪里出错了?

【问题讨论】:

    标签: javascript reactjs redux redux-saga


    【解决方案1】:

    不确定是否正确。尝试使用来自redux-sagaput。如下所示

    import { put } from 'redux-saga/effects';
    
    function* yourGenerator() {
      /*Your code*/
      yield put({ type: 'YOUR_ACTION', YOUR_PAYLOAD });
    }
    

    阅读有关使用 saga here 的调度操作的更多信息。

    【讨论】:

    • 所以这是另一种方法,但我无法从响应函数中触发生成器函数。如果我在 API 调用之后的最终 .then 函数中有 yield put 行,那么我会收到一个错误,说 yield 是一个保留字
    • 不要像普通的 js 承诺那样使用生成器函数。可以看这个例子github.com/ItsMrAkhil/mern/blob/master/app/containers/TasksPage/…
    猜你喜欢
    • 2017-01-17
    • 2019-10-11
    • 1970-01-01
    • 2016-07-27
    • 2020-07-20
    • 2016-11-18
    • 1970-01-01
    • 2017-02-01
    • 2018-05-21
    相关资源
    最近更新 更多