这个问题在这里已经有了答案:
React - User-Defined JSX Components Not rendering
(1 个回答)
4年前关闭。
我正在尝试创建一个使用 mapStateToProps 订阅商店的容器。我能够以这种方式使用 reducer 改变状态
export default function firstReducer(state={}, action) {
switch(action.type){
case 'ADD_USERNAME':
return Object.assign({}, state, {
username: action.payload
});
default:
return state;
}
}
但是, mapStateToProps 甚至一次都没有被调用。我哪里错了
export default class myComponent extends React.Component{
render(){
return(
<h1>this.props.userName</h1>
)
}
}
function mapStateToProps(state){
console.log("Hey");
return{
userName: state.username
};
}
export const myContainer = connect(mapStateToProps, null)(myComponent);
最佳答案
你需要注意的两件事
首先让您的组件名称不是大写字母,然后从组件中删除导出默认值,否则当您将其作为默认值导入时,您将不会使用与商店连接的组件
class MyComponent extends React.Component{
render(){
return(
<h1>this.props.userName</h1>
)
}
}
function mapStateToProps(state){
console.log("Hey");
return{
userName: state.username
};
}
export default connect(mapStateToProps, null)(MyComponent);
关于reactjs - mapStateToProps 根本没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44474031/