Redux 和 React Native 组件连接:this.props 未定义

Redux & React Native component connect: this.props is undefined

我正在尝试访问我的减速器初始状态中定义的名称字段。目前,this.props 返回未定义。

我的减速器:

import { combineReducers } from 'redux';

const INITIAL_STATE = {
    name: "Test"
}

const userReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
      default:
        return state
    }
};

export default combineReducers({
  user: userReducer,
});

正在呈现的组件(此记录 "Props: undefined"):

const AddName = ({ navigation }) => {

    ...

    console.log("Props: ", this.props)

    return (
        <>
        ...
        </>
    )
}

mapStateToProps = (state) => {
    return{
      user : state.user
    };
}

export default connect(mapStateToProps, null)(AddName)

正在创建 redux 存储和提供程序:

...
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from './src/reducers/userReducer';

const store = createStore(reducer)

const AppContainer = () => 
    <Provider store={store} >
        <App />
    </Provider>


AppRegistry.registerComponent(appName, () => AppContainer);

您正在使用功能组件,因此您应该以这种方式使用道具:

const AddName = (props) => {

...

console.log("Props: ", props)

return (
    <>
    ...
    </>
 ) 
}

您正在使用功能组件,this 关键字不适用于功能组件,而是应用于 class 组件。

如下更改您的组件:

class AddName extends React.Component {

    ...

    console.log("Props: ", this.props)

    render(){
    return (
        <>
        ...
        </>
    )

     }

}

mapStateToProps = (state) => {
    return{
      user : state.user
    };
}

export default connect(mapStateToProps, null)(AddName)

希望对您有所帮助。有疑问请随意

您应该使用 class 组件而不是函数组件。 阅读更多相关信息。

https://codeburst.io/react-js-understanding-functional-class-components-e65d723e909