我正在尝试在react组件上显示商店值。但是返回未定义。我的动作和减速器工作正常并更新状态。
但是组件应该在每次状态更改时重新呈现。似乎mapStateToProps或connect函数无法正常工作。
这是我的代码:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {Provider, connect} from 'react-redux';
import {createStore} from 'redux';
class Sam extends Component{
constructor(props){
super(props)
}
render(){
return(
<div>
{this.props.globalState.no} // Uncaught TypeError: Cannot read property 'no' of undefined
<button onClick={()=>{store.dispatch(incAction)}}>Click Me</button>
</div>
)
}
}
const reducer = (state={name:'Piyush',no:0}, action) => {
if(action.type==='INC'){
console.log("INC");
console.log("getstate => ", store.getState());
console.log("Old state => ", state);
console.log("New State => ", Object.assign({}, state, {no:state.no + 1}));
return Object.assign({}, state, {no:state.no + 1})
}
return state;
}
const incAction = {
type:'INC'
}
const mapStateToProps = (globalState) => {
return {globalState:globalState.reducer}
}
const store = createStore(reducer);
ReactDOM.render(<Provider store={store}><Sam /></Provider>, document.getElementById('app'))
export default connect(mapStateToProps)(Sam)
答案 0 :(得分:1)
您的mapStateToProps
似乎不正确。它应该是这样的:
const mapStateToProps = (globalState) => {
return {globalState};
}
由于您当前的mapStateToProps
只返回{globalState: globalState.reducer}
,因此当您尝试访问this.props.globalState.no
时,它不存在,因为globalState.reducer
不存在。您的globalState
看起来像{name:'Piyush',no:0}
。