自动添加当前用户的地理位置

时间:2016-06-07 12:28:42

标签: reactjs redux

我还是Redux的新手。

我希望我的应用管理一系列地点。我已关注Official TODOList tutorial并将TODO替换为Place s。好的开始:))

现在,我想使用Geolocation API自动添加当前用户的位置。

我有一个<PlaceInput>容器,当触发dispatch事件addPlace时。

但我想知道在哪里添加逻辑以添加当前用户&#39;的地方。

1。在根文件?

let store = createStore(placesApp);

// update the store immediately if available

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

我不是这个策略的忠实粉丝,因为地理定位授权需要第一次用户操作,这使得它本质上是异步的。

2。在&#34;假&#34;这样做的容器?

class AddUserGeolocation extends React.Component {

  static propTypes = {
    alreadyAsked: React.PropTypes.bool.isRequired
  }

  componentDidMount {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        dispatcher(addPlace('You', position.coords.latitude, position.coords.longitude))
      });
      dispatcher(askedForUserLocation())
    }
  };

  render() {
    let result = this.props.alreadyAsked ? 'Asked' : 'Not yet'
    return (
      <div>
        {result}
      </div>
    )
  }
}

1 个答案:

答案 0 :(得分:1)

您可以将此信息存储在商店中。 :d 所有逻辑都在您的reducer中处理。像这样:

const initialState = {
    places: [],
    alreadyAsked: false
};

const placesReducer = (state = [], action) => {
    switch(action.type) {
        case 'ADD_PLACE':
            return [...state, action.place];
        default:
            return state;
    }
};

const askReducer = (state = false, action) => {
    switch(action.type) {
        case 'ASK':
            return true;
        default:
            return state;
    }
};

const appReducers = combineReducers({
    places: placesReducer,
    alreadyAsked: askReducer
});

let store = createStore(initialState, appReducers);

// update the store immediately if available

render(
        <Provider store={store}>
            <App />
        </Provider>,
        document.getElementById('root')
);

@connect(
    state => ({
        places: state.places,
        alreadyAsked: state.alreadyAsked
    }),
    dispatcher => ({
        addPlace: (who, lat, long) => ({ type: 'ADD_PLACE', {who, lat, long}}),
        askedForUserLocation: () => ({ type: 'ASK' })
    })
)
class AddUserGeolocation extends React.Component {

    static propTypes = {
        alreadyAsked: React.PropTypes.bool.isRequired
    }

    componentDidMount() {
        const { addPlace, askedForUserLocation } = this.props

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition((position) => {
                dispatcher(addPlace('You', position.coords.latitude, position.coords.longitude))
            });
            dispatcher(askedForUserLocation())
        }
    }

    render() {
        let result = this.props.alreadyAsked ? 'Asked' : 'Not yet'
        return (
            <div>
                {result}
            </div>
        )
    }
}