简体   繁体   English

从异步操作中反映redux显示数据

[英]React redux display data from async action

I am building a react app and implementing redux for data. 我正在构建一个react应用程序并实现redux for data。 When I navigate to a particular route, I want to dispatch the action to fetch the data from an external API and then once the data comes back, display the data for the user. 当我导航到特定路线时,我想调度操作以从外部API获取数据,然后一旦数据返回,就显示用户的数据。

Store : 商店:

import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import { syncHistoryWithStore } from 'react-router-redux';
import { browserHistory } from 'react-router';

import rootReducer from '../reducers/index';

const initialState = {
  marvel :{
    characters: []
  }
};

const store = createStore(rootReducer, initialState, applyMiddleware(thunkMiddleware, createLogger()));

export const history = syncHistoryWithStore(browserHistory, store);

if (module.hot) {
  module.hot.accept('../reducers/', () => {
    const nextRootReducer = require('../reducers/index').default;
    store.replaceReducer(nextRootReducer);
  });
}

export default store;

reducer : 减速机:

import * as constants from '../constants/constants';

const initialState = {
  characters: [],
  isFetching: false,
  errorMessage: null
};

const marvelReducer = (state = initialState, action) => {
  switch (action.type) {
    case constants.FETCH_MARVEL : 
      return Object.assign({},state,{isFetching: true});
    case constants.FETCH_MARVEL_SUCCESS :
      return Object.assign({}. state,{
        characters: [...action.response],
        isFetching: false
      });
    case constants.FETCH_MARVEL_ERROR :
      return Object.assign({}, state,{
        isFetching: false,
        errorMessage: action.message
      });
    default :
      return state;
  }
};

export default marvelReducer;

actions: 动作:

import 'whatwg-fetch';

import * as constants from '../constants/constants';


export const fetchMarvel = (dispatch) => {
  const MARVEL_API = 'http://gateway.marvel.com:80/v1/public/characters?apikey=e542b1d89f93ed41b132eda89b9efb2c';

  dispatch({
    type: constants.FETCH_MARVEL
  });

  return fetch(MARVEL_API).then(
    response => {
      dispatch({
        type: constants.FETCH_MARVEL_SUCCESS,
        response
      });
    },
    error => {
      dispatch({
        type: constants.FETCH_MARVEL_ERROR,
        message: error.message || 'Something went wrong with fetchMarvel'
      });
    });
};

component : 零件 :

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/actions';
import '../styles/homeStyles.css';

class Home extends Component {
  render() {
    const { characters, isFetching, errorMessage } = this.props;
    return (
      <div>
        <h1>React Starter App</h1>
        <h2>This is the home page</h2>
      </div> 
    );
  }
}

function mapStateToProps(state) {
  return {
    characters: state.characters,
    isFetching: state.isFetching,
    errorMessage: state.errorMessage
  };
}

function mapDispatchToProps(dispatch) {
  return { actions: bindActionCreators(actions, dispatch) };
}

export default connect(mapStateToProps, mapDispatchToProps)(Home);

I know I'm not currently displaying the props anywhere in the application, but first I am just trying to get them populated. 我知道我目前没有在应用程序的任何地方显示道具,但首先我只是想让它们填充。 What step am I missing to dispatch the action so that I can populate the props from state? 我错过了什么步骤来发送动作,以便我可以从州填充道具?

You are not dispatching the action anywhere. 你不是在任何地方派遣行动。 So nothing happens. 没有任何反应。
You probably want to do this in a React lifecycle hook, for example: 您可能希望在React生命周期钩子中执行此操作,例如:

class Home extends Component {
  componentDidMount() {
    this.props.actions.fetchMarvel();
  }

  render() {
    const { characters, isFetching, errorMessage } = this.props;
    return (
      <div>
        <h1>React Starter App</h1>
        <h2>This is the home page</h2>
      </div> 
    );
  }
}

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

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