react redux:当使用Connect for mapStateToProps和mapDispatchToProps时仍然为this.props获取空对象

时间:2017-09-18 20:51:14

标签: javascript reactjs redux react-redux create-react-app

我试图在React Redux上学习本教程(https://medium.com/@stowball/a-dummys-guide-to-redux-and-thunk-in-react-d8904a7005d3),但是当我打印出this.props时,我得到一个空对象。看起来mapStateToProps实际上并没有设置this.props,因为反应还没有被调用,但是我不确定为什么

状态应该是这样的(就像在教程中一样),我所做的只是将组件名称ItemList更改为Home

enter image description here

这是我得到的(没有映射到州):

enter image description here

动作/ items.js

export function itemsHasErrored(bool) {
    return {
        type: 'ITEMS_HAS_ERRORED',
        hasErrored: bool
    };
}

export function itemsIsLoading(bool) {
    return {
        type: 'ITEMS_IS_LOADING',
        isLoading: bool
    };
}

export function itemsFetchDataSuccess(items) {
    return {
        type: 'ITEMS_FETCH_DATA_SUCCESS',
        items
    };
}

export function itemsFetchData(url) {
    return (dispatch) => {
        dispatch(itemsIsLoading(true));

        fetch(url)
            .then((response) => {
                if (!response.ok) {
                    throw Error(response.statusText);
                }

                dispatch(itemsIsLoading(false));

                return response;
            })
            .then((response) => response.json())
            .then((items) => dispatch(itemsFetchDataSuccess(items)))
            .catch(() => dispatch(itemsHasErrored(true)));
    };
}

组件/ Home.js

export class Home extends Component {
  componentDidMount() {
    console.log(this.props)
  }

 render() {

    if (this.props.hasErrored) {
      return <p>Sorry! There was an error loading the items</p>;
    }

    if (this.props.isLoading) {
        return <p>Loading…</p>;
    }

  return (
      <ul>
          {this.props.items.map((item) => (
              <li key={item.id}>
                  {item.label}
              </li>
          ))}
      </ul>
  );    

  }
}


 const mapStateToProps = (state) => {
  return {
      items: state.items,
      hasErrored: state.itemsHasErrored,
      isLoading: state.itemsIsLoading
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
      fetchData: (url) => dispatch(itemsFetchData(url))
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);

减速器/ index.js

export function itemsHasErrored(state = false, action) {
    switch (action.type) {
        case 'ITEMS_HAS_ERRORED':
            return action.hasErrored;

        default:
            return state;
    }
}

export function itemsIsLoading(state = false, action) {
    switch (action.type) {
        case 'ITEMS_IS_LOADING':
            return action.isLoading;

        default:
            return state;
    }
}

export function items(state = [], action) {
    switch (action.type) {
        case 'ITEMS_FETCH_DATA_SUCCESS':
            return action.items;

        default:
            return state;
    }
}

存储/ configureStore.js

import { applyMiddleware, createStore } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'

export default function configureStore(initialState) {
    return createStore(
        rootReducer,
        initialState,
        applyMiddleware(thunk)
    )
} 

App.js

import React, { Component } from 'react'
import { Provider } from 'react-redux'
import configureStore from './store/configureStore'

import { Home }                     from './components/Home'
const store = configureStore()

export default class App extends Component {

    render () {
      return (
        <Provider store={store}>
          <Home />
        </Provider>
      )
    }

  }

index.js(我正在使用create-react-app样板)

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

1 个答案:

答案 0 :(得分:12)

问题是您要导出两个组件...未连接(通过指定的导出Homeexport class Home...)并连接(通过export default)。然后,您将导入并呈现未连接的组件:

import { Home } from './components/Home'

由于您要使用已连接的组件,您应该像这样导入默认导出:

import Home from './components/Home'

您可能只想导出连接的组件,除非您有理由使用未连接的组件。