使用 Redux Store 连接 React 组件

igg*_*012 0 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);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试在 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);
Run Code Online (Sandbox Code Playgroud)

这是我的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));
            });
    };
}
Run Code Online (Sandbox Code Playgroud)

这是我的减速器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

我在这里缺少什么?

KA0*_*A01 5

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

  • 发生在我们所有人身上。有时,一组额外的眼睛会有所帮助。 (3认同)