javascript - 使用react-redux而不是有效负载时,操作中的值未定义

标签 javascript reactjs react-redux

我正在使用 React、React-redux、Redux、Express 和 Sequelize 为学校项目构建一个应用程序。

在我的其他 View 中,我取回了数据,以相应地插入和更新我的 View ,但在这种情况下,我得到未定义

我刚刚从 redux 切换到react-redux,所以我提前道歉!

这是我的控制台的屏幕截图:

enter image description here

这是我的 SingleCountry reducer ,还有我的 Action 创建者和 thunk...

'use strict';

import axios from 'axios';

// ACTION TYPES
const GET_COUNTRY = 'GET_COUNTRY';

// ACTION CREATORS
export function getCountry(oneCountry) {
  const action = {
    type: GET_COUNTRY,
    oneCountry,
  };
  return action;
}

//THUNK CREATORS

export function fetchCountry(countryId) {
  return function thunk(dispatch) {
    return axios
      .get('/api/countries/' + `${countryId}`)
      .then(res => res.data)
      .then(country => {
        const action = getCountry(country);
        dispatch(action);
      });
  };
}

// REDUCER
const reducer = function(state = [], action) {
  switch (action.type) {
    case GET_COUNTRY:
      return action.oneCountry;
    default:
      return state;
  }
};

export default reducer;

这是国家/地区的 reducer :

'use strict';

import axios from 'axios';

// ACTION TYPES
const GET_COUNTRIES = 'GET_COUNTRIES';

// ACTION CREATORS
export function getCountries(countries) {
  const action = {
    type: GET_COUNTRIES,
    countries,
  };
  return action;
}

//THUNK CREATORS
export function fetchCountries() {
  return function thunk(dispatch) {
    return axios
      .get('/api/countries')
      .then(res => res.data)
      .then(countries => dispatch(getCountries(countries)))
      .catch(console.error);
  };
}

// REDUCER
const reducer = function(state = [], action) {
  switch (action.type) {
    case GET_COUNTRIES:
      return action.countries;
    // return { ...state, countries: action.countries };
    default:
      return state;
  }
};

export default reducer;

这是 TopFiveCountries 的 reducer :

'use strict';

import axios from 'axios';

// ACTION TYPES
const GET_TOP_COUNTRIES_BY_GFI = 'GET_TOP_COUNTRIES_BY_GFI';

// ACTION CREATORS
export function getTopFiveCountriesByGFI(topFiveCountries) {
  const action = {
    type: GET_TOP_COUNTRIES_BY_GFI,
    topFiveCountries,
  };
  return action;
}

//THUNK CREATORS
export function fetchTopFiveCountriesByGFI() {
  return function thunk(dispatch) {
    return axios
      .get('/api/countries/top-five-countries')
      .then(res => res.data)
      .then(countries => {
        const action = getTopFiveCountriesByGFI(countries);
        dispatch(action);
      })
      .catch(console.error);
  };
}

// REDUCER
const reducer = function(state = [], action) {
  switch (action.type) {
    case GET_TOP_COUNTRIES_BY_GFI:
      return action.topFiveCountries;
    // return { ...state, topFiveCountries: action.topFiveCountries };
    default:
      return state;
  }
};

export default reducer;

这是 SingleCountry 问题的 View :

import React, { Component } from 'react';
import { fetchCountry } from '../reducers/oneCountry';
import { connect } from 'react-redux';
import store from '../store';

class SingleCountry extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const flagStyle = {
      height: '50px',
      width: '100px',
    };

    const oneCountry = this.props.oneCountry;
    return (
      <div className="row">
        <div className="twelve columns">
          <h2> - Single Country -</h2>

          <table className="u-full-width">
            <thead>
              <tr>
                <th>Name</th>
                <th>GFI</th>
                <th>Flag </th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>{oneCountry.name}</td>
                <td>{oneCountry.GFI}</td>
                <td>
                  <img style={flagStyle} src={oneCountry.flagUrl} />
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    );
  }
}

const mapDispatch = dispatch => ({
  fetchCountry: countryId => {
    dispatch(fetchCountry(countryId));
  },
});

const mapState = state => ({
  oneCountry: state.oneCountry,
});

export default connect(mapState, mapDispatch)(SingleCountry);

我的直觉告诉我它要么在我的 axios 请求中,要么在映射和调度的一些语法中。

顺便说一句,我至少得到了部分渲染(见下文)......并且没有错误。是否可以采取任何预防措施来更好地进行诊断?

enter image description here

任何帮助将不胜感激!

更新 这就是我的 store.js 文件的样子...

import { createStore, applyMiddleware, combineReducers } from 'redux';
import loggingMiddleware from 'redux-logger'; // https://github.com/evgenyrodionov/redux-logger
import thunkMiddleware from 'redux-thunk'; // https://github.com/gaearon/redux-thunk
import { composeWithDevTools } from 'redux-devtools-extension';

import topFiveCountriesByGFIReducer from './reducers/topFiveCountriesByGFI';
import countriesReducer from './reducers/countries';
import oneCountryReducer from './reducers/oneCountry';

const middleware = [loggingMiddleware, thunkMiddleware];

const rootReducer = combineReducers({
  topFiveCountries: topFiveCountriesByGFIReducer,
  countries: countriesReducer,
  oneCountry: oneCountryReducer,
});

export default createStore(rootReducer, composeWithDevTools(applyMiddleware(...middleware)));

更新

我最近遇到的错误:

enter image description here

最佳答案

所以你没有 dispatch 你的行动。您必须分派(dispatch)该操作,并且由于它是异步的,因此最好显示某种 UI 来指示您正在从某种 API 中获取数据。这是一个精简版:

class SingleCountry extends Component {
  constructor(props) {
    super(props)

    this.state = {
      loading: true
    }
  }

  componentDidMount() {
    const countryId = this.props.match.params.id;
    dispatch(this.props.fetchCountry(countryId))
      .then(() => {
        this.setState({
          loading: false
        });
      });
  }

  render() {
    const oneCountry = this.props.oneCountry;
    const loading = this.state.loading;
    return (
      <div className="row">
        <div className="twelve columns">
          <h2> - Single Country -</h2>

          {
            !loading ?
              <table className="u-full-width">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>GFI</th>
                    <th>Flag </th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>{oneCountry.name}</td>
                    <td>{oneCountry.GFI}</td>
                    <td>
                      <img style={flagStyle} src={oneCountry.flagUrl} />
                    </td>
                  </tr>
                </tbody>
              </table>
            :
              <img src={LOADING ICON HERE} />
          }
        </div>
      </div>
    );
  }
}

const mapState = (state, ownProps) => ({
  oneCountry: state.oneCountry,
  ...ownProps
});

它的作用是最初将 loading 的状态设置为 true。然后,当组件安装时,您的请求将发送到 API。同时,当请求正在运行时,将显示一个加载图标。请求完成后,调度的 then 将执行并将 loading 的状态设置为 false。这将依次重新渲染您的组件并显示带有适当数据的表格。

此外,请注意 mapState 现在使用第二个参数 - ownProps。问题是,当您将组件连接到 Redux 存储时,您会丢失传递给该组件的所有 props。在这种情况下,React Router 将匹配的参数传递给 SingleCountry,但由于 connect 而丢失。这可以通过使用 mapStatemapDispatch 的第二个参数来解决。第二个参数包含允许传递给连接的组件的 Prop ,您可以将它们传播到返回的对象中以在组件中访问它们。

关于javascript - 使用react-redux而不是有效负载时,操作中的值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47745024/

相关文章:

javascript - 无法将 props 传递给 React Native 导航 v2 中的其他组件

javascript - 如何使用react-router v4获取mapStateToProps中的params值?

reactjs - React-redux 组件不会在存储状态更改时重新渲染

javascript - 在 Razor 中将小数字段显示为 Int

css - 如何水平居中 MUI 网格元素中的元素?

javascript - 通过 jQuery 访问被单击的元素内的 <li> 的最简单方法是什么?

javascript - 更新组件时 react 输入元素不更新

javascript - 使用 Webpack 进行仅调试页面

javascript - 将内联样式更改为样式组件

javascript - 加载特定于代码点火器 View 的独特 JavaScript 文件