6

在以下示例中,如何在地理定位请求期间禁用该按钮?在初始化时未设置 this.props.inProgress ,我想在请求 getCurrentPosition 时禁用按钮并在 RECEIVE_LOCATION 解决时启用。什么是正确的做法?我是否要使用状态并将道具复制到 GeoButton?

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()
4

1 回答 1

9

在 redux 中做 async 的时候,经常需要调用 dispatch 两次。一个同步,一个异步。

您的操作应如下所示:

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 标志。reducer 可以从 action 类型中派生它。

于 2015-11-22T11:26:52.070 回答