首页 > 解决方案 > 数据未在容器中使用 React-Redux(来自 mapStateToProps)传递到组件视图

问题描述

我正在制作一个简单的“React-Redux”实现示例。但是,似乎由于某种原因,我没有得到我应该从商店获得的价值。另外,请注意:

我不知道为什么数据无法通过。有人可以帮我吗?

主页.js

import React, {Component} from 'react';

class Home extends Component {

  constructor(){
    super();
    console.log("***", this.props);
  }

  render(){
    return (
      <div>
        <p>city: {this.props.city}</p>
        <p>Total Customers: {this.props.no_of_customers}</p>
      </div>
    )
  }
}

export default Home;

homeContainer.js

import {connect} from 'react-redux';
import Home from '../components/home';
import actions from '../redux/actions/index';

mapStateToProps = (state, ownProps) => {
  return {
    city: state.reducer2.city,
    name: state.reducer2.no_of_customers
  }
}

mapDispatchToProps = (dispatch) => {
  return {
    addData(newData){
      dispatch(actions.add_item(newData));
    }
  }
}

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

store.js

import { createStore } from 'redux';
import  rootReducer  from '../reducers/index';

const store = createStore (rootReducer);

export default store;

减速器/index.js

import { combineReducers } from 'redux';
import reducer1 from './reducer1';
import reducer2 from './reducer2';

const rootReducer = combineReducers({reducer1, reducer2});

export default rootReducer;

reducer2.js

const initialState = {
  total_customers: 999,
  city: "chicago"
};

const reducer2 = (state = initialState, action) => {

  switch(action.type){

    case "CHANGE_CITY": {
      return {
        ...state,
        city: "london"
      }
    }

    default: {
      return state;
    }
  }

}

export default reducer2;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from './redux/store/index';
import { Provider } from 'react-redux';

ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));

serviceWorker.unregister();

输出:

在此处输入图像描述

我在完整的代码中找不到一个问题!

标签: javascriptreactjsreduxreact-redux

解决方案


将您的代码更改为,

主页.js

constructor(props){
  super(props);
  console.log("***", this.props);
}

在类组件中初始化构造函数时。您应该在任何其他语句之前调用super(props) 。否则, this.props 将在构造函数中未定义。


推荐阅读