使用redux-form,如何根据ASYNC redux状态设置initialValues?

时间:2017-06-29 02:09:34

标签: reactjs react-redux react-redux-form

我正在使用react redux-form。我正在创建一个React组件,允许用户编辑他们的个人资料。

以下是我如何为redux-form设置initalValues:

import * as profilesActions from '../../actions/profilesActions';
....
const mapStateToProps = state => {
  return {
    currentUser: state.currentUser,
    currentUserProfile: state.profiles.find(el => el.id === state.currentUser.user_id),
    initialValues: {
      first_name: state.currentUserProfile.first_name,
      last_name: state.currentUserProfile.last_name
    }
  };
};

问题是现在这是错误的:

Uncaught TypeError: Cannot read property 'first_name' of undefined

原因是用户的个人资料尚未加载到state.profiles ...

如何在initialValues更改时设置currentUserProfile进行设置/更新?

由于

已更新

profilesActions.js

import * as types from './actionTypes';
import ProfilesApi from '../api/ProfilesApi';

export function loadProfileSuccess(profile) {
  return {type: types.LOAD_PROFILE_SUCCESS, profile};
}

export function loadProfile(user_id) {
  return function(dispatch) {
    return ProfilesApi.loadProfile(user_id).then(profile => {
      dispatch(loadProfileSuccess(profile));
    }).catch(error => {
      throw(error);
    });
  };
}

actionTypes

export const LOAD_PROFILE_SUCCESS = 'LOAD_PROFILE_SUCCESS';

更新3

这是我最近的尝试:

export const LOAD_PROFILE_SUCCESS = 'LOAD_PROFILE_SUCCESS';

Profile = connect(
  state => ({
    initialValues: {
      first_name: state.currentUserProfile.first_name,
      last_name: state.currentUserProfile.last_name
    }
  }),
  { profilesActions: LOAD_PROFILE_SUCCESS }               // bind account loading action creator
)(Profile)

这是犯了错误的bindActionCreators expected a function actionCreator for key 'profilesActions', instead received type 'string

1 个答案:

答案 0 :(得分:2)

react-redux connect的第二个参数是一个以dispatch作为参数的函数(参见文档here)。正确的使用方法如下:

Profile = connect(
  state => ({
    initialValues: {
      first_name: state.currentUserProfile.first_name,
      last_name: state.currentUserProfile.last_name
    }
  }),
  dispatch => ({ profilesActions: dispatch({ type : LOAD_PROFILE_SUCCESS }) })
)(Profile)