【问题标题】:Change state from outside the component从组件外部更改状态
【发布时间】:2019-09-14 11:27:51
【问题描述】:

我正在使用带有 expo 的 react native,并尝试在应用程序运行时(活动或后台)获取当前位置更新。但是我不能从外部改变组件的状态。

我尝试使用静态函数将位置从任务管理器方法传递给组件,但它不起作用。

export default class App extends React.Component {

  state = {
    location: null,
    errorMessage: null,
  };

  componentDidMount = async () => {
    await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
      accuracy: Location.Accuracy.Balanced,
      enableHighAccuracy:true,
      timeInterval: 300,
      distanceInterval: 1
    });
  }

  static updateLocation = location => {
    this.setState({ location });
    console.log(this.location);
  }

  render() {
    return (
      ...
    );
  }
}

TaskManager.defineTask(LOCATION_TASK_NAME, ({ data, error }) => {
  if (error) {
    // Error occurred - check `error.message` for more details.
    return;
  }
  if (data) {
    const { locations } = data;
    // do something with the locations captured in the background
    App.updateLocation(locations[0]);
  }
});

我想根据位置更新更改状态。出现的错误是TaskManager: Task "background-location-task" failed:, [TypeError: _class.setState is not a function. (In '_class.setState({ location: location })', '_class.setState' is undefined)]

【问题讨论】:

    标签: javascript reactjs react-native expo


    【解决方案1】:

    在这种情况下,您尝试调用类的函数,而不是渲染的实例。 React 根本无法以这种方式工作。

    状态可以从子组件传递给父组件,但只能通过将状态更新函数作为道具传递给子组件。

    可以通过多种方式在外部管理状态,通常使用 redux 或共享上下文来完成,这可能是您需要的。

    【讨论】:

    • 谢谢,我已经使用 Redux 解决了这个问题,使用了 store.dispatch() 和 store.getState() 方法。
    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 2014-11-19
    • 2020-10-28
    • 2018-07-18
    • 2019-11-23
    • 2016-09-27
    • 1970-01-01
    相关资源
    最近更新 更多