简体   繁体   中英

Redux-thunk not update state in mapstate to props

Hi guys i have a problem in my code any one can help me with redux-thunk

Action.js

import axios from 'axios';
import { API_URL, API_KEY } from './const';

export const FETCH_FLAG_GENDERS = 'FETCH_FLAG_GENDERS';
export const FETCH_FLAG_COUNTRIES = 'FETCH_FLAG_COUNTRIES';
export const FETCH_FLAG_PROVINCES = 'FETCH_FLAG_PROVINCES';
export const FETCH_FLAG_BLOODGROUPS = 'FETCH_FLAG_BLOODGROUPS';
export const FETCH_FLAG_BLOODGROUPTYPES = 'FETCH_FLAG_BLOODGROUPTYPES';



export function fetchFlagProvinces() {
  return async dispatch => {
    function onSuccess(request) {
      dispatch({
        type: FETCH_FLAG_PROVINCES,
        payload: request
      });
      return request;
    }

    function onError(error) {
      console.log(error);
    }

    try {
      const request = axios.get(`${API_URL}/flag/province`, {
        headers: { Authorization: API_KEY }
      });
      return onSuccess(request);
    } catch (error) {
      return onError(error);
    }
  }
}

Reducer

import {
  FETCH_FLAG_GENDERS,
  FETCH_FLAG_PROVINCES,
  FETCH_FLAG_COUNTRIES,
  FETCH_FLAG_BLOODGROUPS,
  FETCH_FLAG_BLOODGROUPTYPES
} from '../actions/flag';
const FLAG_INITIAL_STATE = {
  genderList: [],
  provinceList: [],
  countryList: [],
  bloodGroupList: [],
  bloodGroupTypeList: []
};
export default function( state = FLAG_INITIAL_STATE, action){
  switch(action.type){

    case FETCH_FLAG_PROVINCES:
      console.log('====REDUCER====')
      console.log(action);
      return {
        ...state,
        provinceList: action.payload.data
      };
    break;

    default:
      return state;
  }
}

**

Container

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import { fetchFlagGenders, fetchFlagProvinces, fetchFlagCountries, fetchFlagBloodGroups, fetchFlagBloodGroupsType } from '../../actions/flag';
import { Card, Input, FormGroup, TextArea, Row, Column, Select } from '../../component/bootstrap/';


class PatientForm extends Component {
  async componentWillMount() {
    //this.props.fetchFlagGenders();
    //this.props.fetchFlagProvinces();
    //this.props.fetchFlagBloodGroups();
    //this.props.fetchFlagBloodGroupsType();
    //this.props.fetchFlagProvinces();

    this.props.fetchFlagProvinces()
     .then((response) => {
       console.log('====CONTAINER=====');
       console.log(response.data);
     }, (error) => {
       console.log('fail');
     });


  }


  render() {
    const { handleSubmit } = this.props;
    console.log('===PROP PROVINCE LIST===')
    console.log(this.props.provinceList);
    console.log('===END PROVINCE LIST===')
    return (
      <Row>
        <Card>

        </Card>
      </Row>
    );
  }
}

const validate = (values) => {
  const errors = {};

  if(!values.firstName)
    errors.firstName = 'please enter first name';

  if(!values.lastName)
    errors.lastName = 'please enter last name';

  return errors;
}

const mapStateToProps = (state) => {
  return {
    genderList: state.flags.genderList,
    provinceList: state.flags.provinceList,
    bloodGroupList: state.flags.bloodGroupList,
    bloodGroupTypeList: state.flags.bloodGroupTypeList
  }
}

PatientForm = connect(mapStateToProps, { fetchFlagGenders, fetchFlagProvinces, fetchFlagBloodGroups, fetchFlagBloodGroupsType })(PatientForm);

export default reduxForm({
  validate,
  'form': 'PatientForm'
})(PatientForm);

Index JS

import 'babel-polyfill';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promise from 'redux-promise'
import thunk from 'redux-thunk'
import reducers from './reducers';
import App from './app';

const store = createStore(
  reducers,
  applyMiddleware(thunk)
);
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app'));

Oh forget reducer index.js

import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';

import PatientReducer from './patient_reducer';
import FlagReducer from './flag_reducer';
import ConfigurationReducer from './configuration_reducer';

const rootReducer = combineReducers({
  flags: FlagReducer,
  patients: PatientReducer,
  form: formReducer
});

export default rootReducer;

I have no idea why in container i cannot use this.props.provinceList it said undefined! and also i check from console.log it is promise but it seem like when promise complete it not update the state can anyone help me please .

Here is api url http://demo3918385.mockable.io/flag/province

Note 1: In container this.props.fetchFlagProvinces() is can fetch data properly everythink working ok start with promise end ending with data

And also where the code should i improve please let me know. Thank

You forgot await keyword in front of your axios' request. You get a Promise because you don't wait for it to be processed.

try {
  const request = await axios.get(`${API_URL}/flag/province`, {
    headers: { Authorization: API_KEY }
  });
  return onSuccess(request);
} catch (error) {
  return onError(error);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM