【问题标题】:Really quick question on how to reference state variables within render() - React Native关于如何在 render() 中引用状态变量的快速问题 - React Native
【发布时间】:2020-12-01 06:07:29
【问题描述】:

认为这是一个简单的语法问题,但也许这是一个更大的概念,我不了解层次结构和继承。

我正在用 react native (expo) 创建一个应用程序。我想显示一张以用户为中心且持续更新的地图(我最终将使用 watchCurrentPositionAsync,但由于我是新手,我只想尝试收集一次位置信息,然后从那里弄清楚)。当输入纬度和经度的原始值时,下面的代码成功显示了地图,但我似乎无法从状态对象中提取值以在 render() 中使用。

标有//RIGHT HERE 的行是我想使用保存在我的状态对象中的纬度/经度值的地方 - 现在我将它们设置为常量,以便我的应用程序运行。

我尝试将这些常量替换为:

this.state.initLat_s
this.state[initLat_s]

我尝试创建另一个结构“regData”并引用它的多种方式,包括引用它以获取 initialRegion 的所有信息,包括增量

我在状态内外都创建了“get()”函数,这会引发错误

我尝试使用正确的值创建“全局”变量(例如 lat_g)并使用 this.lat_g、lat_g 和许多其他语法来引用它们,但我根本无法让编译器理解对渲染中的状态变量。

export default class App extends React.Component {

  state = { //state set
    locationResult: null, //location result holds either location object converted to string or error message as string 
    locationStatus: null, //holds success status of location grab
    initLat_s: null, //holds initial latitude and longitude of user location
    initLon_s: null
  }; 
  
  componentDidMount() {this._getLocationAsync();} //if component mounts, run location grabber
    
  _getLocationAsync = async () => { //location grabber
    let { status } = await Permissions.askAsync(Permissions.LOCATION); //ask for location perms
    if (status !== "granted") { //if location perms denied, set locationResult accordingly
      this.setState({locationResult: "Permission to access location was denied"});
      this.setState({locationStatus: false});
    } else {
      let initLocation = await Location.getCurrentPositionAsync({}); //otherwise, save location object in "location" var
      this.setState({locationResult: JSON.stringify(initLocation)}); //set locationResult to string representation of location
      this.setState({locationStatus: true});

      let {initLat, initLon} = initLocation.coords; //gather lat/lon from location object
      this.setState({initLat_s: initLat}); //set lat/lon in state accordingly
      this.setState({initLon_s: initLon});
    }
  };

  render() {
    return (
      <View style={styles.container}>
        <MapView 
          style={styles.mapStyle}
          initialRegion={{
            latitude: -30,     //RIGHT HERE
            longitude: 120,    //RIGHT HERE
            latitudeDelta: .01,
            longitudeDelta: .01 
          }}
        />
      </View>
    );
  }
}

【问题讨论】:

  • 不,这是我尝试的第一件事,因为我认为这是 JavaScript 的正确语法,但它似乎不起作用:/ 它在 expo 中给出“Unexpected keyword 'this'”,并且在 VSCode 中,它从编译器给出“:预期”

标签: javascript reactjs react-native maps expo


【解决方案1】:

你可以试试这个方法。

constructor(props) {
    super(props);
    this.state = {
      locationResult: null, //location result holds either location object converted to string or error message as string 
    locationStatus: null, //holds success status of location grab
    initLat_s: null, //holds initial latitude and longitude of user location
    initLon_s: null
    }
  }

【讨论】:

  • 不幸的是,我尝试了这个,它产生了我在回复 Aymen 时提到的相同错误 - “意外关键字'this'”
  • 也许这与您的 state 属性无关,而是可能缺少构造函数和超级属性。
  • 我不太清楚你的意思。我需要“App”类的构造函数吗?有什么地方我可以阅读更多有关此的信息吗?另外,我不太清楚“超级道具”是什么意思。
  • 成功了,谢谢!我没有意识到我需要创建那个构造函数:)。 “位置抓取器”功能仍然不起作用,因此它只是默认为状态对象中设置的任何值,而不是从用户那里收集的值,但这是一个单独的问题。谢谢!
【解决方案2】:

试试这个,它会对你有用。

    // Initial state shouldn't be a **null** because initialRegion.latitude and 
   // initialRegion.longitude are marked as required
    
        state = {
            initLat_s: -30, 
            initLon_s: 120,
          };
        <MapView
                  initialRegion={{
                    latitude: this.state.initLat_s, // Without {}
                    longitude: this.state.initLon_s, // Without {}
                    latitudeDelta: 0.01,
                    longitudeDelta: 0.01,
                  }}
                />

【讨论】:

  • 虽然这是正确的(所以我给了你一个赞成票!),但问题是缺少构造函数:)
  • 我建议你使用函数式组件并使用反应钩子而不是类组件来设置状态。对初学者来说简单明了。
猜你喜欢
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
  • 2021-01-22
  • 1970-01-01
  • 2023-03-28
  • 2018-10-31
  • 2023-01-24
相关资源
最近更新 更多