mapStateToProps 根本没有被调用 [英] mapStateToProps not getting called at all

查看:41
本文介绍了mapStateToProps 根本没有被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个使用 mapStateToProps 订阅商店的容器.我能够以这种方式使用减速器更改状态

I am trying to create a container which is subscribed to the store using mapStateToProps. I am able to change the state using reducers in this fashion

export default function firstReducer(state={}, action) {
    switch(action.type){
        case 'ADD_USERNAME':
            return Object.assign({}, state, {
                username: action.payload
            });
        default:
            return state;
    }
}

然而,mapStateToProps 甚至没有被调用一次.我哪里错了

However, mapStateToProps is not getting called even once. Where am I going wrong

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);

推荐答案

需要注意的两件事

首先让您的组件名称不使用大写字母,然后从组件中删除导出默认值,否则当您将其作为默认值导入时,您将不会使用与商店连接的组件

First have you component name not being with Uppercase letter and second remove the export default from the component, otherwise when you will be importing it as default you wouldn't be using the component that you have connected the store with

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);

这篇关于mapStateToProps 根本没有被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆