【问题标题】:Redux-thunk not update state in mapstate to propsRedux-thunk 不会将 mapstate 中的状态更新为 props
【发布时间】:2017-08-10 09:58:23
【问题描述】:

大家好,我的代码有问题,任何人都可以帮助我解决 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);
    }
  }
}

减速器

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

**

容器

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

索引 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'));

哦忘了减速器 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;

我不知道为什么在容器中我不能使用 this.props.provinceList 它说未定义!而且我从console.log检查它是promise,但似乎promise完成后它不会更新状态任何人都可以帮助我。

这里是 api 网址http://demo3918385.mockable.io/flag/province

注意 1:在容器中 this.props.fetchFlagProvinces() 可以正常获取数据,一切正常,以承诺开始,以数据结束

还有我应该改进代码的地方,请告诉我。 谢谢

【问题讨论】:

    标签: reactjs redux redux-thunk


    【解决方案1】:

    您忘记了 axios 请求前面的 await 关键字。你得到一个 Promise 是因为你没有等待它被处理。

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

    【讨论】:

    • 你救了我的命
    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2019-08-31
    • 2022-01-05
    • 2021-11-07
    相关资源
    最近更新 更多