Warm tip: This article is reproduced from stackoverflow.com, please click
react-native redux

React native mapDispatchToProps not working

发布于 2020-03-27 10:30:41

I can't get my mapDispatchToProps to work properly.

I export a combineReducers:

export default combineReducers({
  auth: AuthReducer,
  tenants: TenantsReducer
});

The tenants reducer:

const INITIAL_STATE = {
  error: false,
  data: [],
  tenantData: {},
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case GET_TENANTS_DATA:
      return { ...state, error: false, data: action.payload };
    case GET_TENANT_DATA:
        return { ...state, error: false, tenantData: action.payload };
    default:
      return state;
  }
};

Then I have getTenantByID method in my action

export const getTenantByID = ({ tenantID }) => {
  return (dispatch) => {
    const getTenant = {
      FirstName: 'Jonh', LastName: 'Doe', Email: 'jonh@test.com', Phone: 'xxx-xxx-xxxx',
      Unit: '101', MiddleName: '',
    };
    dispatch({
      type: GET_TENANT_DATA,
      payload: getTenant
    });
  };
};

Finally, I tried to use it in my component.

import { connect } from 'react-redux';
import { getTenantByID } from '../actions';
...

componentDidMount() {
    const { navigation } = this.props;
    const tenantID = navigation.getParam('tenantID', '0');
    this.props.getTenantByID(tenantID);
      console.log(this.props); 
    this.state = {
      tenantData: this.props.tenantData
    };
  }

const mapStateToProps = ({ tenants }) => {
  return {
    error: tenants.error,
    tenantData: tenants.tenantData
  };
};

const mapDispatchToProps = () => {
     return {
          getTenantByID
     };
};

export default connect(mapStateToProps, mapDispatchToProps)(TenantDetails);

In my componentDidMount, the console.log(this.props) is returning a empty object for tenantData. What am I doing wrong?

Questioner
myTest532 myTest532
Viewed
100
mosabbir tuhin 2019-07-04 05:00

Initial state is showing as the component already mounted, which is empty object {}

this.props.getTenantByID(tenantId);

this action triggers actually, but the data is not available in componentDidMount lifecycle.

try putting log in render like this


  componentDidMount(){
    this.props.getTenantByID(2);
  }
  render() {
    console.log(this.props.tenantData); // 1st render => {}, 2nd render=> desired data
    return (
      <div/>
    );
  }