gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:28:52 24 4
gpt4 key购买 nike

我对 Redux 还很陌生。

我希望我的应用程序能够管理地点列表。我已经关注了Official TODOList tutorial并替换TODOPlace 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com