【问题标题】:Connecting React Component with Redux Store将 React 组件与 Redux Store 连接起来
【发布时间】:2017-06-03 11:09:12
【问题描述】:

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 加载到仪表板数组中并呈现为 &lt;p&gt; 标签,只显示 title 值。不幸的是,它没有发生。

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

我在这里错过了什么?

【问题讨论】:

  • 我认为你的减速器有错字。 switch(action.types) 应该是 switch(action.type) 没有's'。
  • 你是个天才。

标签: redux react-redux


【解决方案1】:

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

【讨论】:

  • 现在好了。这很尴尬。
  • 发生在我们所有人身上。有时,多一双眼睛会有所帮助。
猜你喜欢
  • 2020-05-05
  • 2017-12-17
  • 2019-12-26
  • 1970-01-01
  • 2018-04-02
  • 2018-08-25
  • 1970-01-01
  • 2016-11-11
  • 2020-06-21
相关资源
最近更新 更多