使用mapDispatchToProps的Redux连接容器不起作用

时间:2018-06-24 05:41:07

标签: reactjs redux react-redux

我正在学习Redux。我正在尝试将调度功能从容器组件连接到演示组件。

容器组件:

foo

Presentational组件

//FILE : app/javascript/packs/containers/registration.js 

import { connect } from 'react-redux'

import { fetchCountry } from '../actions'

import Countries from '../components/registration/countries';

const getCountry = (state, filter) => {
  switch (filter) {
  case 'region':
  console.log("Get Country Triggered",state)
  default:
  console.log("Get Country Default Triggered",state)
 }
}

const mapStateToProps = state => ({
  countries:getCountry(state,'region')
})

const mapDispatchToProps = dispatch => ({
  fetchCountry: region => dispatch(fetchCountry(region))
})

export default connect(
  mapStateToProps, 
  mapDispatchToProps
)(Countries)

操作:

// FILE : /app/javascript/packs/components/registration/countries.jsx

import React from 'react'
import PropTypes from 'prop-types'

const Countries = ({ fetchCountry }) => (
  <ul>
    <li> 
     <button onClick={() => fetchCountry('region')}>Get Country</button> 
    </li>
  </ul>
)

Countries.propTypes = {
  fetchCountry: PropTypes.func.isRequired
}

减速器

//FILE : /app/javascript/packs/actions/index.js

/* Action types */

export const FETCH_COUNTRY = "FETCH_COUNTRY";
export const FETCH_CITY = "FETCH_CITY";

/* Action creators */

export function fetchCountry(region) {
  return { type: FETCH_COUNTRY, region };
}

当我尝试加载页面时,我是fetchCountry是未定义的错误。

// FILE: /app/javascript/packs/reducers/fetchPlace.js const fetchPlace = (state = [], action) => { switch (action.type) { case 'FETCH_COUNTRY': console.log('FETCH COUNTRY Reducer'); default: return state } } export default fetchPlace fetchCountry warning.js:33 Warning: Failed prop type: The prop国家is marked as required in未定义, but its value is

我了解,我在这里缺少一些基础知识,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

也许这是您的问题。取决于您是否有index.js

import { fetchCountry } from '../actions'

应该是

import { fetchCountry } from '../actions/action_file_name'