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

Express 如何在redux中进行外部api调用,express,reactjs,redux,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 = ini

我的代码如下:

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')
    };
}
我正在使用示例作为初学者工具包。我想对example.com/api进行基于承诺的api调用,但我无法使用异步调用。我在中间件中遇到错误,无法读取未定义的承诺。我的中间件代码如下所示

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>
);
}
}
import React,{Component,PropTypes}来自'React';
从“redux”导入{bindActionCreators};
从'react redux'导入{connect};
从'redux/modules/info'导入{load};
@connect(state=>({info:state.info.data}),dispatch=>bindActionCreators({load},dispatch))
导出默认类信息栏扩展组件{
静态类型={
信息:PropTypes.object,
加载:需要PropTypes.func.isRequired
}
render(){
const{info,load}=this.props;//eslint禁用行无阴影
const styles=require('./InfoBar.scss');
返回(
这是一个信息栏
{' '}
{info?info.message:'no info!'}
{info&&new Date(info.time).toString()}
从服务器重新加载
);
}
}

这只是减速器。您可能希望创建一个操作。某个操作触发将使redux存储更新其状态的事件。redux的基本流程如下所示:

  • 安装组件
  • 行动
  • 分派的操作将通过
    提供程序
    组件更新存储
  • 这将触发组件的重新渲染
下面是使用
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()) }
}

检查一下

我正在使用的客户端中间件,上面有代码,如果我调用可以工作的localhost api,但它不能与外部api调用一起工作,也可以使用该示例。localhost api的代码类似于导出默认函数loadInfo(){return new Promise((resolve)=>{resolve({message:'这来自api服务器',时间:Date.now()});});}这不是一个正确的答案,因为他使用redux tunk作为中间产品。并且打破了流程我担心在对远程端点执行异步HTTP请求时会遇到同源限制。看一看,也许您会知道如何代理您的请求或以另一种方式克服限制。我使用了初学者工具包,您的代码看起来是正确的。我同意上面的@Rishat。。。看起来您做的一切都很好,但您可能正在进行一个失败的跨域REST调用。在“中间件错误”之后,您在控制台中获得了更多信息吗?我没有得到跨源错误,但我得到了“无法读取未定义的属性‘承诺’错误”。API适用于跨域访问。我修复了xhr请求的错误,但现在它可以将简单json API作为假数据使用,但不能使用从数据库返回数据的真实API调用,因为加载API请求需要时间,不能使用简单json