简体   繁体   English

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

[英]react redux: still getting empty object for this.props when using Connect for mapStateToProps and mapDispatchToProps

I'm trying to follow this tutorial ( https://medium.com/@stowball/a-dummys-guide-to-redux-and-thunk-in-react-d8904a7005d3 ) on React Redux but am getting an empty object when I print out this.props. 我正在尝试在React Redux上关注本教程( https://medium.com/@stowball/a-dummys-guide-to-redux-and-thunk-in-react-d8904a7005d3 )但是当我得到一个空对象时我打印出这个.props。 It seems like mapStateToProps isn't actually setting this.props since react redux's connect isn't being called, but I'm not sure why 似乎mapStateToProps实际上并没有设置this.props,因为反应redux的连接没有被调用,但我不知道为什么

This is what the state should be (like in the tutorial), all I did was change the component's name ItemList to Home 这就是状态应该是什么(就像在教程中一样),我所做的就是将组件的名称ItemList更改为Home

在此输入图像描述

Here's what I'm getting (nothing was mapped to the state): 这是我得到的(没有映射到状态):

在此输入图像描述

actions/items.js 动作/ 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)));
    };
}

components/Home.js 组件/ 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);

reducers/index.js 减速器/ 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;
    }
}

store/configureStore.js 存储/ 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 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 (I am using create-react-app boilerplate) 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();

The issue is that you're exporting two components... the non-connected (via the named export Home with export class Home... ) and connected (via export default ). 问题是您要导出两个组件...非连接(通过命名导出Homeexport class Home... )并连接(通过export default )。 Then, you're importing and rendering the non-connected component: 然后,您要导入并呈现未连接的组件:

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

Since you want to use the connected component, you should be importing the default export like this: 由于您要使用连接的组件,您应该导入默认导出,如下所示:

import Home from './components/Home'

You may want to just export the connected component, unless you have some reason to use the unconnected one. 您可能只想导出连接的组件,除非您有理由使用未连接的组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在没有任何mapstatetoprops的情况下在redux中连接,并且仍然将其作为props - connect in redux without any mapstatetoprops and still getting things as props 链接redux连接mapStateToProps,以访问mapDispatchToProps内部的道具 - Chaining redux connect mapStateToProps , to access props inside mapDispatchToProps 反应this.props是一个空对象 - React this.props is an empty object 链接connect / mapStateToProps / mapDispatchToProps函数以在react-redux中重用代码 - Chain connect/mapStateToProps/mapDispatchToProps functions for code reuse in react-redux Redux连接在初始加载时未调用mapStateToProps或mapDispatchToProps - Redux connect not calling mapStateToProps or mapDispatchToProps on initial load 了解 React-Redux 中的 mapStateToProps 和 mapDispatchToProps - Understanding mapStateToProps & mapDispatchToProps in React-Redux 如何使用react-redux连接mapStateToProps,MapDispatchToProps和redux-router - How use react-redux connect with mapStateToProps,MapDispatchToProps and redux-router React + Redux connect(mapStateToProps) - React + Redux connect (mapStateToProps) 使用redux时,在reactjs中克隆我们在this.props中收到的道具 - cloning the props that we receive in this.props in reactjs when using redux 无法通过this.props访问响应对象| React / Redux - Not able to access response object via this.props | React/ Redux
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM