javascript - 数据未在容器中使用 React-Redux(来自 mapStateToProps)传递到组件视图
问题描述
我正在制作一个简单的“React-Redux”实现示例。但是,似乎由于某种原因,我没有得到我应该从商店获得的价值。另外,请注意:
控制台中没有错误或警告。
在“home.js”(构造函数内部)中执行 console.log 时,props 传递的值显示为 undefined。
我不知道为什么数据无法通过。有人可以帮我吗?
主页.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();
输出:
我在完整的代码中找不到一个问题!
解决方案
将您的代码更改为,
主页.js
constructor(props){
super(props);
console.log("***", this.props);
}
在类组件中初始化构造函数时。您应该在任何其他语句之前调用super(props) 。否则, this.props 将在构造函数中未定义。
推荐阅读
- python - 如何查询共享 VPC 网络?
- c# - str.Split(".") 不在 C# 交互式窗口中工作,但在 C# .Net 核心项目中工作?
- javascript - 将变量作为标题传递给css
- python - django.db.utils.IntegrityError: UNIQUE 约束在序列化程序上调用我的 .save() 函数时失败
- react-native - 无法在 react-redux 中存储 DocumentSnapshot 导致分页时超出最大调用堆栈大小错误
- html - 如何在 Rmarkdown 中保存 html 输出
- c# - 子元素切换到折叠或隐藏后网格没有变化
- javascript - 不允许在渐进式 Web 应用程序中进行屏幕打印 - angular / reactjs
- python - 使用 Pandas Agg 功能计算分位数
- ruby-on-rails - 如何在 Rails 的一个产品(属性)中创建一组用户(室友)