我将发布代码并在最后提出问题。
SignUpScreen.js
export default class SignUpScreen extends Component {
constructor(props) {
super(props);
}
validateConfirmationPassword() {
const { username } = this.props;
console.log("TEST >> " + username);
}
render() {
const { username, password, email, confirmPassword } = this.props;
<Input
placeholder="Username"
value={username}
onChangeText= {(value) => this.props.onChangeText('username', value)}
/>
<Button
onPress={() => this.validateConfirmationPassword()}
/>
}
SignUpScreen_reducer.js
export default function reducer(state={
username: '',
email: '',
password: '',
confirmPassword: '',
usernameError: false,
emailError: false,
passwordError: false,
}, action) {
const { type, payload } = action
switch(type) {
case 'ON_CHANGE_UI_FIELD' : {
return {...state, [payload.key]: payload.value}
}
default: {
return state
}
}
SignUpScreenContainer.js
const mapStateToProps = (state) => {
return {
...state,
}
}
const mapDispatchToProps = (dispatch) => {
return {
onChangeText: (key, value) => {
dispatch(onChangeField(key, value))
},
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SignUpScreen);
SignUpScreen_actions.js
export function onChangeField(key, value) {
return (dispatch) => {
dispatch({type: 'ON_CHANGE_UI_FIELD', payload: {key, value}})
}
}
PS:我删除了不必要的部分代码(例如按钮和输入文本)。如果需要更多代码,请告诉我。
我的问题是:我在做什么错?我不断在console.log(“ TEST”)上获取用户名,密码,电子邮件和其他所有内容的“未定义”。我的商店设置正确。我还可以看到动作和化简器上收到的值以及正确的“键”和“值”。
任何帮助将不胜感激。预先感谢。
答案 0 :(得分:1)
您需要做两件事来解决此问题。首先,正如其他人提到的那样,您需要在构造函数中绑定validateConfirmationPassword()
,以确保函数在被onPress
调用时具有正确的上下文:
constructor(props) {
super(props);
this.validateConfirmationPassword = this.validateConfirmationPassword.bind(this);
}
第二,您需要调整尝试访问username
的方式。您表示在state
内登录mapStateToProps()
时,会看到诸如{ "signUpScreenReducer": { "email": "", "emailError": false, "password": "", "passwordError": false, "username": "", "usernameError": false, }
之类的对象。您正在尝试以username
的身份访问const { username } = this.props;
,但是所有内容都嵌套在属性signUpScreenReducer
中。您需要像这样访问它:
const { username } = this.props.signUpScreenReducer;
或者您可以将mapStateToProps()
更改为Object,以传播signUpScreenReducer
(state.signUpScreenReducer)对象的实际属性:
const mapStateToProps = ({ signUpScreenReducer }) => {
return {
...signUpScreenReducer,
}
}
您甚至不需要传播,您也可以:
const mapStateToProps = ({ signUpScreenReducer }) => signUpScreenReducer;
希望有帮助!
答案 1 :(得分:0)
-只需将您的validateConfirmationPassword函数替换为以下版本。
validateConfirmationPassword = () => {
const { username } = this.props;
console.log("TEST >> " + username);
}
或按如下所示在构造函数中对该函数进行绑定
constructor(props) {
super(props);
this.validateConfirmationPassword = this.validateConfirmationPassword.bind(this);
}