使用Redux Saga从API获取信息

时间:2019-04-29 22:16:45

标签: reactjs redux redux-saga

我正在学习Redux Saga,并试图在每次渲染组件时调用API,并将API的响应保存在State对象中。我这样实现了Component

import React, { Component } from "react";
import { Container } from "./styles";
import { withRouter } from "react-router-dom";
import { bindActionCreators } from "redux";
import * as ratesActions from "../../stores/actions/rates";
import { connect } from "react-redux";

class Main extends Component {
  componentDidMount() {
    ratesActions.updateRate();
  }

  render() {
    return (
      <Container>
        <div>
          <h1>Hi there!</h1>
        </div>
      </Container>
    );
  }
}

const mapStateToProps = state => ({
  rates: state.rates
});

const mapDispatchToProps = dispatch =>
  bindActionCreators(ratesActions, dispatch);

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(Main));

我想每次componentDidMount都调用updateRate()操作。这是updateRate()动作:

export function updateRate() {
  return {
    type: "ASYNC_RATE_UPDATED"
  };
}

执行此操作是因为,如果我在其中放入console.log,我可以看到它正在工作。

然后,我创建了sagas

import api from "../../services/api";
import { call, put, takeLatest, all } from "redux-saga/effects";

export function* updateRateAsync() {
  try {
    const response = yield call(api.get("public/rates/all"));

    yield put({
      type: "RATE_UPDATE_SUCCEEDED",
      response: response.data
    });
  } catch (error) {
    yield put({
      type: "RATE_UPDATE_FAILED",
      message: error.message
    });
  }
}

export function* watchUpdateRates() {
  yield takeLatest("ASYNC_RATE_UPDATED", updateRateAsync);
}

export default function* root() {
  yield all([watchUpdateRates()]);
}

还有我的减速器:

export default function rates(state = [], action) {
  switch (action.type) {
    case "RATE_UPDATE_SUCCEEDED":
      console.log(action.response[0]["exchange_rate"]);
      return {
        ...state,
        rates: {
          ves: action.response[0]["exchange_rate"],
          brl: null,
          ars: null,
          inr: null,
          zar: null
        }
      };
    default:
      return state;
  }
}

但是,我的saga不会收听我的action,也不会执行API调用。我在做什么错了?

谢谢!

1 个答案:

答案 0 :(得分:1)

这是您的代码中的错误。 您需要在componentDidMount中而不是this.props.updateRate()中调用ratesActions.updateRate()

const mapDispatchToProps = dispatch => bindActionCreators(ratesActions, dispatch);

上一行将rateActions对象中的所有动作绑定到组件的道具。

更新:

根据您的评论,由于您尚未定义状态,因此状态为null。通过redux connect注入的数据将通过props而不是state可用。因此您必须在组件

中访问类似this.props.rates的费率