React native redux map state to props not working

2019-01-26 21:52发布

问题:

I am new to react-native and I am trying to implement a simple sign up functionality using react-redux. For some reasons , mapping the state to props in connect is not working.

Below is my code :

SignUp.js ( Component )

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

This my root reducer

export default function getRootReducer(navReducer) {
    return combineReducers({
        nav: navReducer,
        signUpReducer : signUpReducer,
    });
}

The register user function is being called. And the fetch request is also successfully executed over a network. It returns the same user object back after storing it in a database. It dispatches to the storeUser function as well. The reducer is getting called as well.

But , for some reasons , the state is not mapped to the props inside the connect. this.props.user returns undefined.

I must be doing something wrong in this but I am not able to figure it out. Based on what I have seen till now when we dispatch any action using bindActionCreators the result from reducer needs to be mapped to component's props using connect. Please correct me if wrong.

Please help me with this issue.

回答1:

From your store defination,

return combineReducers({
        nav: navReducer,
        signUpReducer : signUpReducer,
    });

You defined the key signUpReducer for your SignUp component state. In order to access the state of this component,you should use this key followed by the state name.

The correct way to access user is :

 export default connect(
      state => ({
          user : state.signUpReducer.user 
      })

//use signUpReducer key



回答2:

FOR ME ALSO THIS IS WORKING componentWillReceiveProps(nextProps)

componentWillReceiveProps(nextProps) {

 console.log();
 this.setState({propUser : nextProps.user})
}