我正在尝试访问减速器初始状态中定义的名称字段。目前,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,
});
正在渲染的组件(此日志记录为“道具:未定义”):
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);
答案 0 :(得分:0)
您正在使用Component函数,因此您应该以这种方式使用props:
const AddName = (props) => {
...
console.log("Props: ", props)
return (
<>
...
</>
)
}
答案 1 :(得分:0)
您正在使用功能组件,并且this
关键字不适用于功能组件,而是将其应用于类Components。
按如下所示更改组件:
class AddName extends React.Component {
...
console.log("Props: ", this.props)
render(){
return (
<>
...
</>
)
}
}
mapStateToProps = (state) => {
return{
user : state.user
};
}
export default connect(mapStateToProps, null)(AddName)
希望有帮助。毫无疑问
答案 2 :(得分:0)
您应该使用类组件而不是功能组件。 进一步了解。
https://codeburst.io/react-js-understanding-functional-class-components-e65d723e909