如何在等待 redux 解析时禁用按钮?

How to disable a button while waiting for redux to resolve?

在下面的示例中,如何在地理定位请求期间禁用按钮?在初始化时未设置 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()

在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 类型中导出它。