语言:Reactjs 和 vanilla JavaScript
这个问题更多的是一个普通的 JavaScript 回调问题,但我将添加我的 React 代码来展示我是如何陷入这种困境的。
让我们看看,塔伦蒂诺风格,在我令人困惑的错误:
我正在尝试发送回调作为成功回调的参数
navigator.geolocation.getCurrentPosition(success(dataLoaded), error, options);
但它不喜欢,因为根据文档,“pos”被认为是成功回调的“唯一输入参数” 。
现在让我们倒带并弄清楚是什么让我陷入了这个混乱:
我使用回调作为一种方式,让我的 React 应用程序竖起大拇指,表明异步获取已完成并呈现自身。
onDataLoaded: function() {
this.setState({
postsLoaded: true,
});
},
componentDidMount: function(){
WebAPIUtils.fetchComponentData(this.onDataLoaded);
},
render: function() {
if(!this.state.postsLoaded){
return (<div className="Loading">Loading...</div>);
}
return (
<div>
//Components can be rendered now since their data is loaded.
</div>
);
}
一旦下面的代码成功,我需要执行该回调:
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
//Here I want to execute my callback to render.
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
但是 geolocation.getCurrentPosition 已经规定了回调,因此似乎无法将该回调作为成功回调的参数传递
有没有办法将该回调作为成功回调的额外参数传递?作为回调的参数发送的回调看起来很奇怪,但是形成我的原始回调来处理位置模块之外的位置逻辑也感觉很俗气。