将React组件与Redux Store连接

时间:2017-01-18 21:54:29

标签: redux react-redux

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属性仍然是一个空数组,而不是显示返回的数据......

我在这里缺少什么?

1 个答案:

答案 0 :(得分:4)

你的减速机上有一个拼写错误。 switch(action.types)应为switch(action.type)而不是&#39;