2015-11-22 42 views
2

在以下示例中,如何在地理位置請求期間禁用按鈕?在this.props.inProgress沒有設置在init上,我想在請求getCurrentPosition時禁用按鈕,如果解決了RECEIVE_LOCATION則啓用。什麼是正確的方法?我是否使用狀態和複製道具到GeoButton?如何在等待redux解決時禁用按鈕?

export function getGeolocation() { 
    return dispatch => { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function(position) { 
     dispatch({ 
      type: 'RECEIVE_LOCATION', 
      coords: { 
      latitude: position.coords.latitude, 
      longitude: position.coords.longitude, 
      inProgress: false, 
      }, 
     }); 
     }); 
    } 
    } 
} 
export function geolocation(state={}, action) { 
    switch (action.type) { 
    case 'RECEIVE_LOCATION': 
     var newState = action.coords; 

     return newState; 
    default: 
     return state; 
    } 
} 


class GeoButton extends React.Component { 
    constructor(props) { 
    super(props); 
    } 

    findLocation(e) { 
    e.preventDefault(); 
    this.props.dispatch(getGeolocation()); 
    } 
    render() { 
    console.log(this.props); // on init geolocation object is empty 
    var self = this; 
    return (
     <div> 
     <button type="button" onClick={this.findLocation} disabled={self.props.geolocation.inProgress}>Get location</button> 
     </div> 
    ) 
    } 
} 

export default connect(state => ({ 
    geolocation: state.geolocation 
}))(GeoButton); // just gives it dispatch() 
+0

不能使用inProgress標誌?像disabled =「inProgress」 – Radu

+0

是不是更好的設置對應於預期數據的構造函數狀態對象,並解決時,然後用此數據替換此狀態?我不確定在這種情況下哪種方法是正確的,目前的解決方案不起作用。 – luzny

回答

4

在redux中進行異步時,通常需要調用兩次。一個同步,一個異步。

你的行動應該是這個樣子:

export function getGeolocation() { 
    return dispatch => { 
    dispatch({ type: 'FETCHING_LOCATION' }); 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition((position) => { 
     dispatch({ 
      type: 'RECEIVE_LOCATION', 
      coords: { 
      latitude: position.coords.latitude, 
      longitude: position.coords.longitude 
      } 
     }); 
     }); 
    } 
    }; 
} 

而且你的減速應該是這樣的。我調整了狀態對象的結構,將應用程序數據與UI數據分開。

export function geolocation(state = {}, action) { 
    switch (action.type) { 
    case 'RECEIVE_LOCATION': 
     return { 
     coords: action.coords, 
     inProgress: false 
     }; 
    case 'FETCHING_LOCATION': 
     return { 
     coords: null, 
     inProgress: true 
     }; 
    } 
    return state; 
} 

沒有必要在行動創建者中設置inProgress標誌。減速器可以從動作類型中派生出來。