语言:Reactjs 和 vanilla JavaScript
这个问题不仅仅是一个一般的 JavaScript 回调问题,但我将添加我的 React 代码来展示我是如何陷入这种困境的。
让我们以塔伦蒂诺的风格来看看我犯的令人困惑的错误:
我正在尝试发送回调作为成功回调的参数
navigator.geolocation.getCurrentPosition(success(dataLoaded), error, options);
但它不喜欢,因为根据docs,“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 有 prescribed callbacks因此,似乎无法将该回调作为成功回调的参数传递
有没有办法将该回调作为成功回调的额外参数传递?作为回调的参数发送的回调看起来很奇怪,但形成我的原始回调来处理位置模块外部的位置逻辑也感觉很俗气。
最佳答案
使用bind !
navigator.geolocation.getCurrentPosition(
success.bind(null, dataLoaded),
error,
options);
//
function success(dataLoaded, 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.');
dataLoaded();
}
这实际上创建了一个新版本的函数,您可以在其中替换 this
并预填充参数。因此,传递给 getCurrentPosition
的回调是一个单参数函数,调用时将成为 success
函数中的 pos
。
关于JavaScript - 将参数添加到成功回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32852797/