将 React 组件与 Redux Store 连接

Connecting React Component with Redux Store

react-redux 的非常基本的简单 GET 示例

我有一个 "MockAPI" 模拟对 API 的 GET 请求,如下所示:

const dashboards = [
  {
    "Id":1,
    "title":"Overview"
  },
  {
    "Id":2,
    "title":"Overview"
  },
  {
    "Id":3,
    "title":"Overview"
  },
  {
    "Id":4,
    "title":"Overview"
  }
];

class DashboardApi {
  static getAllDashboards() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(Object.assign([], dashboards));
      }, delay);
    });
  }
}

我正在尝试开发一个 react-redux 流程,通过单击按钮分派一个动作,然后通过 redux 存储更新组件。

这是我的组件代码:

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import * as dashboardActions from '../../actions/dashboardActions';

class HomePage extends React.Component {
  constructor(props) {
    super(props);
    this.loadDashboards = this.loadDashboards.bind(this);
  }

  loadDashboards() {
    this.props.dispatch(dashboardActions.loadDashboards());
  }

  dashboardItem(dashboard, index) {
    return <p key={index}>{dashboard.title}</p>;
  }

  render() {
    return (
      <div>
          <h1>
            Hello World!
            <button onClick={this.loadDashboards}>load</button>
          </h1>
          {this.props.dashboards.map(this.dashboardItem)}
      </div>
    );
  }
}

HomePage.propTypes = {
  dashboards: PropTypes.array.isRequired,
  dispatch: PropTypes.func.isRequired
};

function mapStateToProps(state) {
  return {
    dashboards: state.dashboards
  };
}

export default connect(mapStateToProps)(HomePage);

这是我的 dashboardActions.js

import * as types from './actionTypes';
import dashboardApi from '../mockApi/mockDashboardApi';

export function loadDashboardsSuccess(dashboards) {
    return { type: types.LOAD_DASHBOARDS_SUCCESS, dashboards };
}

export function loadDashboards() {
    return dispatch => {
        return dashboardApi
            .getAllDashboards()
            .then(dashboards => {
                dispatch(loadDashboardsSuccess(dashboards));
            });
    };
}

这是我的减速器:

import initialState from './initialState';
import * as types from '../actions/actionTypes';

export default function dashboardReducer(state = initialState.dashboards, action) {
    switch(action.types) {
        case types.LOAD_DASHBOARDS_SUCCESS:
            return action.dashboards;

        default:
            return state;
    }
}

我正在尝试让 onClick 加载到仪表板数组中并呈现为 <p> 标签,仅显示 title 值。不幸的是,它没有发生。

我看到 LOAD_DASHBOARDS_SUCCESS 操作正在加载,但我看到商店中的 dashboards 属性 仍然是一个空数组,而不是显示返回的数据。 .

我在这里错过了什么?

你的减速器有错字。 switch(action.types) 应该是 switch(action.type) 没有 's'