如何在redux中进行外部api调用

时间:2016-11-29 20:42:45

标签: express reactjs redux

我的代码如下:

const LOAD = 'redux-example/LOAD';
const LOAD_SUCCESS = 'redux-example/LOAD_SUCCESS';
const LOAD_FAIL = 'redux-example/LOAD_FAIL';
import axios from 'axios';
const initialState = {
    loaded: false
};
export default function info(state = initialState, action = {}) {
    switch (action.type) {

    case LOAD:
    return {
    ...state,
    loading: true
   };
   case LOAD_SUCCESS:
  return {
    ...state,
    loading: false,
    loaded: true,
    data: action.result
  };
case LOAD_FAIL:
  return {
    ...state,
    loading: false,
    loaded: false,
    error: action.error
  };
default:
  return state;
}
}
export function load() {
    return {
        types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
        promise: (client) => client.get('http://example.com/getdata')
    };
}

我使用https://github.com/erikras/react-redux-universal-hot-example示例作为入门套件。我想基于api调用example.com/api进行promise。但是我无法用异步调用来做。我在中间件中得到错误,无法读取undefined的承诺。我的中间件代码如下所示。

export default function clientMiddleware(client) {
return ({dispatch, getState}) => {
return next => action => {
    if (typeof action === 'function') {
        return action(dispatch, getState);
    }
    const { promise, types, ...rest } = action; // eslint-disable-line no-redeclare
    if (!promise) {
        return next(action);
    }
    const [REQUEST,SUCCESS,FAILURE] = types;
    next({...rest, type: REQUEST});
    const actionPromise = promise(client);
    actionPromise.then(     
        (result) => next({...rest, result, type: SUCCESS}),
        (error) => next({...rest, error, type: FAILURE})
    ).catch((error)=> {
        console.error('MIDDLEWARE ERROR:', error);
        next({...rest, error, type: FAILURE});
    });
    return actionPromise;
};
};
}

我的组件代码如下

import React, {Component, PropTypes} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {load} from 'redux/modules/info';

@connect(state => ({info: state.info.data}),dispatch =>      bindActionCreators({load}, dispatch))

export default class InfoBar extends Component {
static propTypes = {
info: PropTypes.object,
load: PropTypes.func.isRequired
}
render() {
const {info, load} = this.props; // eslint-disable-line no-shadow
const styles = require('./InfoBar.scss');
return (
  <div className={styles.infoBar + ' well'}>
    <div className="container">
      This is an info bar
      {' '}
      <strong>{info ? info.message : 'no info!'}</strong>
      <span className={styles.time}>{info && new Date(info.time).toString()}</span>
      <button className="btn btn-primary" onClick={load}>Reload from server</button>
    </div>
  </div>
);
}
}

1 个答案:

答案 0 :(得分:-1)

这只是减速器。您可能想要创建一个动作。操作会触发将使redux存储更新其状态的事件。对于类似的东西,redux的基本流程如下:

  • 安装组件
  • 派遣行动
  • 依次调度的操作将通过Provider组件
  • 更新商店
  • 这将触发重新渲染组件。

以下是使用fetch的基本示例。

import fetch from 'isomorphic-fetch';

export function getUsers() {
  return dispatch => {
    dispatch({ type: REQUEST_USERS });

    return fetch('/api/v1/users')
      .then(res => res.json())
      .then(users => {
        dispatch({ type: RECEIVE_USERS, payload: users });
        return users;
      });
  }
}

然后您可以在组件级别项目中调用它。

import { getUsers } from 'actions/users';

class UserList extends Component {
  componentDidMount() { dispatch(getUsers()) }
}

查看example