javascript - 从异步操作中 react redux 显示数据

标签 javascript reactjs redux

我正在构建一个 React 应用程序并为数据实现 redux。当我导航到特定路线时,我想分派(dispatch)操作以从外部 API 获取数据,然后在数据返回后为用户显示数据。

商店:

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;

Action :

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

组件:

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

我知道我目前没有在应用程序的任何地方显示 Prop ,但首先我只是想让它们填充。 我错过了哪一步来发送 Action 以便我可以从状态填充 Prop ?

最佳答案

您不会在任何地方调度操作。所以什么也不会发生。
您可能希望在 React 生命周期 Hook 中执行此操作,例如:

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

关于javascript - 从异步操作中 react redux 显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38057195/

相关文章:

javascript - 监听事件,例如在 JavaScript 中添加新元素

javascript - 如何使用 JavaScript 获取图像大小(高度和宽度)?

javascript - 断言一个值恰好等于 undefined

javascript - 路线应该声明一个屏幕。 [ react native 导航错误]

javascript - 处理不将结果存储在状态中的异步操作

javascript - event.target 和 getelementbyid 之间的区别

css - 如果我已将所有组件嵌套在 Router 内,如何放置 <Login> 组件

javascript - 错误: Babel polyfill is required although its already installed

javascript - Redux 中更新常量时的延迟

javascript - 在子进程中没有处理程序的情况下与 Redux : Passing function to child component, 调用进行 react