2016-08-24 30 views
0

我使用的是反應和終極版,想知道是否以下是可能的:在設定初始狀態前等待Ajax調用反應,和/終極版

我在做一個「編輯表單」組件,我想設置初始狀態preselected爲this.props.user.preselected.id。

我可以在任何地方撥打this.props.user.preselected.id除了設置初始value.I不斷收到一個空值的情況下,我相信這是因爲減速this.props.user只出現後this.props.fetchSingleUser完成。

是否可以將初始狀態設置爲當前在同一個組件中提取的縮減器?

class PropertyEdit extends Component { 

    static contextTypes = { 
    router: PropTypes.object 
    }; 

    constructor(props) { 
     super(props); 
     this.state = { 
      preselected= this.props.user.preselected.id 
     };  
    } 


    componentWillMount() { 
    this.props.fetchSingleUser(this.props.params.id); 
    } 

.... 


function mapStateToProps(state) { 
    return { 
    user:state.user.single 
    }; 
} 


function mapStateToProps(state) { 
    return { 
    user:state.users.single 
    }; 
} 

action.js

export function fetchSingleUser(id) { 
    return function(dispatch) { 
    axios.get(`${URL}/users/${id}`) 
    .then(response => { 
     dispatch({ 
     type:FETCH_USER, 
     payload: response 
     }); 
    }) 
    .catch(() => { 
     console.log("Error "); 
    }); 
    } 
} 

減速機:

const INITIAL_STATE = { single: null }; 

export default function(state = INITIAL_STATE, action) { 
    switch (action.type) { 
    case FETCH_USER: 
     return {...state, single: action.payload.data}; 
    } 
    return state; 
} 

回答

0

你不覺得當你接收到的用戶數據,你應該只呈現形式?

  • 使用還原thunk,您可以發出一個操作USER_LOADED一旦完成提取。
  • 這個新的行動將更新userLoaded = true
  • 了Redux商店,那麼你可以通過user.loaded在你的反應組件顯示形式
+0

我只是在我的行動的創建者添加。我認爲這是有道理的。您是否說我在獲取用戶並將其設置爲我的縮減器以顯示在組件中後應該派發另一個操作? – lost9123193

+0

請問您還可以展示您的減速器嗎? – sylvain

+0

當然我加了。 – lost9123193

1

VERRY常見的方法是有一個異步操作

3個行動

types.js

export const FETCH_USER_REQUEST = 'FETCH_USER_REQUEST' 
export const FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS' 
export const FETCH_USER_FAIL = 'FETCH_USER_FAIL' 

reducer.js

import {combineReducers} from 'redux'; 
import * as types from './types'; 

const isFetching = (state = false, action) => { 
    switch (action.type) { 
    case types.FETCH_USER_REQUEST: 
     return true; 
    case types.FETCH_USER_SUCCESS: 
    case types.FETCH_USER_FAIL: 
     return false; 
    default: 
     return state; 
    } 
}; 

const data = (state = {}, action) => { 
    switch (action.type) { 
    case types.FETCH_USER_SUCCESS: 
     return action.payload.data; 
    } 
    return state; 
}; 

export default combineReducers({ 
    isFetching, 
    data 
}); 

所以你可以在你的組件和顯示isFetching道具/隱藏表單

相關問題