我对 Redux 还很陌生。
我希望我的应用程序能够管理地点列表。我已经关注了Official TODOList tutorial并替换TODO
与Place
s。好的开始:)
现在,我想使用 Geolocation API自动添加当前用户的位置(如果可用)。
我有一个<PlaceInput>
容器,当触发时 dispatch
事件 addPlace
。
但我想知道应该在哪里添加逻辑来添加当前用户的位置。
1。在根文档中?
let store = createStore(placesApp);
// update the store immediately if available
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
我不太喜欢这种策略,因为地理定位授权需要用户第一次执行操作,这使得它本质上是异步的。
2。在一个“假”容器中就可以做到这一点?
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>
)
}
}
最佳答案
您可以将此信息存储在商店中。 :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>
)
}
}
关于reactjs - 自动添加当前用户的地理位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37679422/