Expo TaskManager API:在“导出默认值”之外更新状态

BGT*_*ate 6 reactjs react-native expo

我正在创建一个跟踪用户当前位置并每 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)
  }
});
Run Code Online (Sandbox Code Playgroud)

小智 1

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

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)
    }
});
Run Code Online (Sandbox Code Playgroud)

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

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