我是新的反应-本机,我试图实现一个简单的注册功能使用redux。由于某些原因,将状态映射到连接中的道具不起作用。
下面是我的代码:
SignUp.js (组件)
import React from 'react';
import { View, Text , TouchableOpacity , TextInput } from 'react-native';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as signUpActions from "../actions/SignUpActions";
class SignUp extends React.Component {
constructor(){
super();
this.state = {
name : '',
password : '',
};
}
saveUser(){
let user = {};
user.name = this.state.name;
user.password = this.state.password;
this.props.registerUser(user);
}
static navigationOptions = {
title : 'Sign Up',
};
render(){
return (
<View>
<TextInput
placeholder="Username"
onChangeText={(text) => this.setState({name : text})}
/>
<TextInput
placeholder="Password"
onChangeText={(text) => this.setState({password : text})}
/>
<TouchableOpacity onPress = {() => this.saveUser()} >
<Text>DONE</Text>
</TouchableOpacity>
</View>
);
}
}
export default connect(
state => ({
user : state.user
}),
dispatch => bindActionCreators(signUpActions, dispatch)
)(SignUp);SignUpAction.js
function storeUser(user) {
return {
type : 'REGISTER_USER',
payload : user,
};
};
export function registerUser(user) {
return function (dispatch, getState) {
fetch(<the-url>)
.then((response) => {return response.json()})
.then((responseData) => dispatch(storeUser(responseData)))
.catch((err) => console.log(err));
};
};SignUpReducer.js
const initialState = {
data : {},
};
export default function signUpReducer(state = initialState, action) {
console.log(action.payload)
//This gives {id:26 , name : "xyz" ,password:"pass"}
switch (action.type) {
case 'REGISTER_USER' :
return {
...state ,
user : action.payload
}
default :
return state;
}
}这是我的根减速器
export default function getRootReducer(navReducer) {
return combineReducers({
nav: navReducer,
signUpReducer : signUpReducer,
});
}正在调用寄存器用户函数。在中,获取请求也在网络上成功执行。它在数据库中存储相同的用户对象后返回。它还分配给storeUser函数。减速机也被叫来了。
但是,由于某些原因,状态没有映射到连接内的道具。this.props.user返回未定义的。
我在这方面一定做错了什么,但我想不出来。根据我到目前为止所看到的,当我们使用bindActionCreators分派任何操作时,还原器的结果需要使用connect映射到组件的支持。如果错了,请纠正我。
请帮我解决这个问题。
发布于 2017-12-06 15:57:38
从你商店的定义来看,
return combineReducers({
nav: navReducer,
signUpReducer : signUpReducer,
});您为您的signUpReducer组件状态定义了键SignUp。为了访问这个组件的状态,您应该使用这个键,后面跟着状态名称。
访问user的正确方法是:
export default connect(
state => ({
user : state.signUpReducer.user
})//使用signUpReducer密钥
发布于 2018-07-20 18:44:54
对于我来说,这也是工作componentWillReceiveProps(nextProps)
componentWillReceiveProps(nextProps) {
console.log();
this.setState({propUser : nextProps.user})
}https://stackoverflow.com/questions/47677755
复制相似问题