简体   繁体   English

如何在Redux中进行外部API调用反应

[英]How to make external api calls in redux react

My code is as below: 我的代码如下:

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')
    };
}

I am using https://github.com/erikras/react-redux-universal-hot-example example as starter kit. 我正在使用https://github.com/erikras/react-redux-universal-hot-example示例作为入门工具包。 I want to make promise based api call to example.com/api.But I am not able to do it with async call.I get error in middleware that can not read promise of undefined.My middleware code is as below. 我想对example.com/api进行基于Promise的api调用,但是我无法通过异步调用来做到这一点。我在中间件中遇到错误,无法读取未定义的Promise。我的中间件代码如下。

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;
};
};
}

MY component code is as below 我的组件代码如下

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>
);
}
}

this is only the reducer. 这只是减速器。 You would want to create an action. 您将要创建一个动作。 An action triggers the event that will make the redux store update its state. 一个动作触发事件,该事件将使redux存储更新其状态。 The basic flow of redux for something like this goes like: redux的基本流程如下:

  • Mount a component 安装组件
  • Dispatch an action 派遣行动
  • Dispatched action in turn will update the store via the Provider component 调度的动作将依次通过Provider组件更新商店
  • this will trigger a re-render of the component. 这将触发组件的重新渲染。

The following is a basic example using fetch . 以下是使用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;
      });
  }
}

Then you can call this in your component level item. 然后,您可以在组件级项目中调用它。

import { getUsers } from 'actions/users';

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

Check out the example 看看例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM