gpt4 book ai didi

reactjs - 世博任务管理器 API : Updating state outside "export default"

转载 作者:行者123 更新时间:2023-12-03 13:39:11 32 4
gpt4 key购买 nike

我正在创建一个应用程序,用于跟踪用户的当前位置并每 5 秒将数据发送到服务器。我正在使用 expo,有一个名为 TaskManager 的 API,需要在范围之外进行初始化。是否有其他方法可以在不使用 redux 的情况下更新“导出默认值”之外的状态?

export default class App extends Component {
constructor(props){
super(props)


}

state = {
mapRegion: null,
hasLocationPermissions: false,
locationResult: null,
marker: {
latitude: 0,
longitude: 0
},
latitude: 0,
longitude: 0,
location: null,
errorMessage: null
}

componentWillMount() {
this.onLoad();
}
componentDidMount() {
//console.log(store.getState())
}

onLoad = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);

if (status !== 'granted') {
this.setState({
locationResult: 'Permission to access location was denied',
});
} else {
this.setState({ hasLocationPermissions: true });
}

let isRegistered = await TaskManager.isTaskRegisteredAsync(LOCATION_TRACKER)
if (!isRegistered) console.log('yes its waiting status:'+ isRegistered);

await Location.startLocationUpdatesAsync(LOCATION_TRACKER, {
accuracy: Location.Accuracy.High,
timeInterval: 2500,
distanceInterval: 0,
})
}

}

TaskManager.defineTask(LOCATION_TRACKER, ({ data, error }) => {
if (error) {
console.log(error)
// Error occurred - check `error.message` for more details.
return;
}
if (data) {
const { locations } = data;
//Right here, I need to update my state something like,

this.setState({
//...
}); //but ofcourse this not gonna work


console.log(locations)
}
});

最佳答案

您有几种方法可以使其发挥作用。首先,您可以声明一个全局范围变量来存储您当前的位置。

location = null;

TaskManager.defineTask(LOCATION_TRACKER, ({ data, error }) => {
if (error) {
console.log(error)
// Error occurred - check `error.message` for more details.
return;
}
if (data) {
const { locations } = data;
location = locations;
//Right here, I need to update my state something like,

this.setState({
//...
}); //but ofcourse this not gonna work

console.log(locations)
}
});

或者我认为最好的方法是设置一个像 redux 这样的状态容器。

您可以在此处查看所有文档 https://react-redux.js.org/然后在任务管理器中调用操作,您将能够保存当前位置并将当前位置分派(dispatch)给所有连接的组件。

关于reactjs - 世博任务管理器 API : Updating state outside "export default",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54170010/

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