React Native 中的全局变量更新

问题描述 投票:0回答:2

嘿伙计们,我有一个全局变量,可以保存我的项目计数。我有一个类,可以包含一个文本框并在标题上显示我的计数。 当我更新全局变量时..比如 global.variable = 5 然后我将其更新为.. ++global.variable。 它更新了它的值,但当时它无法为该文本框唱小夜曲,并且 该文本框在许多类中使用。 这是我的计数课

    class count  extends Component {
    constructor(props){
      super(props);
      state = {
        xyz:0
      }
    }


    render() {
      return (        
  <Text style={{color:'white',fontSize:10}}>{global.count}</Text>  
    )}
  }
export default count;

这样我就可以使用这个类了

<count />

我希望每当我执行 global.count++ 时,它都可以增加其值并更新文本框中的该值,并且该文本在许多中使用......并且该项目位于标题中 谢谢...

reactjs react-native react-navigation
2个回答
1
投票

您可以将该变量放入您的状态中,每次您想要更新此变量时,您都可以使用 this.setState({ yourvariable : newValue})。在react-native中,当您更改状态时,会再次调用函数render(),因此它将更改您的文本框值。

处理这种全局值的一个好方法是使用 Redux 在您的应用程序中共享全局状态,使用 Redux 您可以保证该值将在您的应用程序的每个需要该值的部分中被访问。您可以在 https://redux.js.org/

阅读有关 redux 的更多信息

0
投票

我发现不使用更多依赖项的最简单方法是发布者/订阅者模式,如博览会论坛上的这个答案中所述。

(复制粘贴,因为链接可能会变坏:)

**选项 1 - 发布者/订阅者模式** 这是一个简单的示例,其中使用“发布者/订阅者”模式在后台跟踪“纬度”和“经度”。正在发生的事情的摘要:
  1. LocationService
    函数通过闭包拥有内部状态。它返回一个带有多个方法的对象。最重要的是要让你头脑清醒的是
    subscribe
    。当调用它时,它会作为参数传递对函数的引用,并且该引用将添加到
    subscribers
    数组中。
  2. componentDidMount
    调用
    locationService.subscribe(this.onLocationUpdate)
    将类方法
    onLocationUpdate
    传递到
    subscribers
    数组中。
  3. 每次收到新数据时,
  4. TaskManager
    都会执行回调。回调包含对
    LocationService.setLocation({latitude, longitude})
    的调用。这将获取
    latLng
    对象并将其传递给
    subscribers
    数组中包含的每个函数。这包括类方法
    onLocationUpdate
    ,因此类
    state
    被更新,从而重新渲染组件。
/* LOCATION SERVICE - PUB/SUB SOLUTION */

/* PUBLISHER */
const LocationService = () => {
  let subscribers = []
  let location = {
    latitude: 0,
    longitude: 0
  }

  return {
    subscribe: (sub) => subscribers.push(sub),
    setLocation: (coords) => {
      location = coords
      subscribers.forEach((sub) => sub(location))
    },
    unsubscribe: (sub) => {
      subscribers = subscribers.filter((_sub) => _sub !== sub)
    }
  }
}

export const locationService = LocationService()

/* SUBSCRIBER */

import * as Location from 'expo-location'
import * as Permissions from 'expo-permissions'
import * as TaskManager from 'expo-task-manager'
import React from 'react'
import { Text, View } from 'react-native'
import { locationService } from './src/locationService'

const LOCATION_TASK_NAME = 'background-location-task'

export default class App extends React.Component {
  state = {
    latitude: 0,
    longitude: 0,
  }

  onLocationUpdate = ({ latitude, longitude }) => {
    this.setState({
      latitude: latitude,
      longitude: longitude
    })
  }

  async componentDidMount() {
    locationService.subscribe(this.onLocationUpdate)
    const { status } = await Permissions.askAsync(
      Permissions.LOCATION,
      Permissions.USER_FACING_NOTIFICATIONS
    )

    if (status === 'granted') {
      await Location.startLocationUpdatesAsync(
        LOCATION_TASK_NAME,
        {
          accuracy: Location.Accuracy.Highest,
          distanceInterval: 1,
          timeInterval: 5000
        }
      )
    }
  }

  componentWillUnmount() {
    locationService.unsubscribe(this.onLocationUpdate)
  }

  render() {
    const { latitude, longitude } = this.state
    return (
      <View>
        <Text>Lat: {latitude}</Text>
        <Text>Lng: {longitude}</Text>
      </View>
    )
  }
}

TaskManager.defineTask(LOCATION_TASK_NAME, ({ data, error }) => {
  if (error) {
    return
  }
  if (data) {
    const { latitude, longitude } = data.locations[0].coords
    locationService.setLocation({
      latitude,
      longitude
    })
  }
})

这是一个简单的示例,其中使用

latitude
模式在后台跟踪
longitude
publisher/subscriber
。正在发生的事情的摘要:

  1. LocationService
    函数通过闭包拥有内部状态。它返回一个带有多个方法的对象。最重要的是要让你头脑清醒的是
    subscribe
    。当调用它时,它会作为参数传递对函数的引用,并且该引用将添加到
    subscribers
    数组中。
  2. componentDidMount
    调用
    locationService.subscribe(this.onLocationUpdate)
    将类方法
    onLocationUpdate
    传递到
    subscribers
    数组中。
  3. 每次收到新数据时,
  4. TaskManager
    都会执行回调。回调包含对
    LocationService.setLocation({latitude, longitude})
    的调用。这将获取
    latLng
    对象并将其传递给
    subscribers
    数组中包含的每个函数。这包括类方法
    onLocationUpdate
    ,因此类
    state
    被更新,从而重新渲染组件。
/* LOCATION SERVICE - PUB/SUB SOLUTION */

/* PUBLISHER */
const LocationService = () => {
  let subscribers = []
  let location = {
    latitude: 0,
    longitude: 0
  }

  return {
    subscribe: (sub) => subscribers.push(sub),
    setLocation: (coords) => {
      location = coords
      subscribers.forEach((sub) => sub(location))
    },
    unsubscribe: (sub) => {
      subscribers = subscribers.filter((_sub) => _sub !== sub)
    }
  }
}

export const locationService = LocationService()

/* SUBSCRIBER */

import * as Location from 'expo-location'
import * as Permissions from 'expo-permissions'
import * as TaskManager from 'expo-task-manager'
import React from 'react'
import { Text, View } from 'react-native'
import { locationService } from './src/locationService'

const LOCATION_TASK_NAME = 'background-location-task'

export default class App extends React.Component {
  state = {
    latitude: 0,
    longitude: 0,
  }

  onLocationUpdate = ({ latitude, longitude }) => {
    this.setState({
      latitude: latitude,
      longitude: longitude
    })
  }

  async componentDidMount() {
    locationService.subscribe(this.onLocationUpdate)
    const { status } = await Permissions.askAsync(
      Permissions.LOCATION,
      Permissions.USER_FACING_NOTIFICATIONS
    )

    if (status === 'granted') {
      await Location.startLocationUpdatesAsync(
        LOCATION_TASK_NAME,
        {
          accuracy: Location.Accuracy.Highest,
          distanceInterval: 1,
          timeInterval: 5000
        }
      )
    }
  }

  componentWillUnmount() {
    locationService.unsubscribe(this.onLocationUpdate)
  }

  render() {
    const { latitude, longitude } = this.state
    return (
      <View>
        <Text>Lat: {latitude}</Text>
        <Text>Lng: {longitude}</Text>
      </View>
    )
  }
}

TaskManager.defineTask(LOCATION_TASK_NAME, ({ data, error }) => {
  if (error) {
    return
  }
  if (data) {
    const { latitude, longitude } = data.locations[0].coords
    locationService.setLocation({
      latitude,
      longitude
    })
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.