[英]Data not getting passed to View of Component using React-Redux (from mapStateToProps) in Container
I am making a simple example of "React-Redux" implementation.我正在制作一个简单的“React-Redux”实现示例。 But, it seems that due to some reason I am not getting the value that I should get from store.
但是,似乎由于某种原因我没有得到我应该从商店得到的价值。 Also, kindly note that:
另外,请注意:
There is no error or warning in Console.控制台中没有错误或警告。
While doing console.log in "home.js" (inside constructor) the value passed of props displays as undefined .在“home.js”(构造函数内部)中执行 console.log 时,props 传递的值显示为undefined 。
I don't have any clue why data is not being able to passed.我不知道为什么数据无法通过。 Can someone help me out?
有人可以帮我吗?
home.js主页.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主页Container.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商店.js
import { createStore } from 'redux';
import rootReducer from '../reducers/index';
const store = createStore (rootReducer);
export default store;
reducers/index.js减速器/ index.js
import { combineReducers } from 'redux';
import reducer1 from './reducer1';
import reducer2 from './reducer2';
const rootReducer = combineReducers({reducer1, reducer2});
export default rootReducer;
reducer2.js减速器2.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索引.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();
Output:输出:
I cannot find a single issue in the complete code!我在完整代码中找不到一个问题!
Change your code to,将您的代码更改为,
Home.js主页.js
constructor(props){
super(props);
console.log("***", this.props);
}
When initiating the constructor in the class component.在类组件中初始化构造函数时。 you should call super(props) before any other statement.
你应该在任何其他语句之前调用super(props) 。 Otherwise, this.props will be undefined in the constructor.
否则, this.props 将在构造函数中未定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.