2017-06-29 49 views
1

我正在使用react redux-form。我正在創建一個React組件,以允許用戶編輯他們的個人資料。使用redux-form,如何基於ASYNC redux狀態設置initialValues?

這裏是我我的工作來設置Redux的形式的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 d當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'; 

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

這是犯錯誤的W¯¯bindActionCreators expected a function actionCreator for key 'profilesActions', instead received type 'string

回答

2

反應,終極版的第二個參數連接是和訊作爲參數的函數(見文檔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)