【发布时间】:2020-04-05 18:54:30
【问题描述】:
我刚开始使用 React 钩子,但遇到了问题。在下面的组件中,我通过 react 钩子更新了一个值,并将其用作函数的参数。问题是钩子是异步的,所以当我调用函数时,值是未定义的。 代码如下:
反应钩子:
const [selectedLocation, setSelectedLocation] = React.useState()
我需要更新selectedLocation的函数:
const sendLocationToDevice = (loader = true) => {
props.dispatch({type: "CLEAR_ERROR"})
const resObj = CalculateBearing({
a: {lat: props.store.position.latitude, long: props.store.position.longitude},
b: {lat: selectedLocation.coordinates.lat, long: selectedLocation.coordinates.lng} // -> here's the value is undefined
})
我更新selectedLocation值的表单:
<View>
{ selectedLocation === null ? (
<GooglePlacesAutocomplete
placeholder='Enter Location'
minLength={2}
autoFocus={false}
returnKeyType={'default'}
fetchDetails={true}
onPress={(data, details = null) => {
setSelectedLocation({name: details.formatted_address, coordinates: details.geometry.location})
sendLocationToDevice()
}}
流程是:用户使用表格选择位置并调用函数计算方位。使用旧的 this.setState 一切都是同步的,所以我没有问题,现在我不确定最好的模式是什么,或者我是否误用了钩子......我应该如何解决这个问题?
【问题讨论】:
标签: javascript reactjs