将一个对象从函数组件传递到类组件。

huangapple go评论61阅读模式
英文:

Pass an object from function component to class component

问题

Map类组件处理位置对象作为参数
```javascript
export default class Map extends React.Component {
  render() {
    const location = this.props.route.params;
    console.log("Map location is: ", JSON.stringify(location));
    return (
      <View style={{ flex: 1 }}>
        <MapView style={{ flex: 1 }} region={region}></MapView>
      </View>
    );
  }
}
const region = {
  latitude: 35.6762,
  longitude: 139.6503,
  latitudeDelta: 0.1,
  longitudeDelta: 0.1,
};

仪表板功能通过导航将位置对象传递给Map类

export default function Dashboard({ navigation }) {
  const [location, setLocation] = useState(false);

  const onGetLocation = async () => {
    const result = requestLocationPermission();
    console.log("Request location permission response: ", result);
    await result.then((res) => {
      console.log("res is:", res);
      if (res) {
        Geolocation.getCurrentPosition(
          async (position) => {
            setLocation(position);
          },
          async (error) => {
            // 查看下面的错误代码表。
            console.log(error.code, error.message);
            setLocation(false);
          },
          { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
        );
      }
    });
    navigation.navigate("Map", location); //位置始终为false??
  };

  return (
    // ...
    // ...
    // ...
  );
}

为什么位置总是设置为false,即使它被设置为当前位置。
我是React Native的新手。我是不是错误地使用了async/await?任何形式的帮助或指导都将不胜感激。


<details>
<summary>英文:</summary>

Map class component handles location object as params

export default class Map extends React.Component {
render() {
const location = this.props.route.params;
console.log("Map location is: ", JSON.stringify(location));
return (
<View style={{ flex: 1 }}>
<MapView style={{ flex: 1 }} region={region}></MapView>
</View>
);
}
}
const region = {
latitude: 35.6762,
longitude: 139.6503,
latitudeDelta: 0.1,
longitudeDelta: 0.1,
};


Dashboard function passes location object to Map class using navigation

export default function Dashboard({ navigation }) {
const [location, setLocation] = useState(false);

const onGetLocation = async () => {
const result = requestLocationPermission();
console.log("Request location permission response: ", result);
await result.then((res) => {
console.log("res is:", res);
if (res) {
Geolocation.getCurrentPosition(
async (position) => {
setLocation(position);
},
async (error) => {
// See error code charts below.
console.log(error.code, error.message);
setLocation(false);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
}
});
navigation.navigate("Map", location); //location is always false??
};

return (
...
...
...


Why does location always sets to false even though it&#39;s set to current location. 
I&#39;m new to react native. Am i incorrectly using aync/await? Any kind of help or guidance is appreciated.

</details>


# 答案1
**得分**: 1

>为什么位置总是设置为false,即使它被设置为当前位置。

实际上它并不是被设置为`false`,而是因为在创建时它最初是`false`,这里导航发生在Promise到达之前,所以这样。

你想要在`.then`块内发生导航,因此你不需要使用状态,只需直接使用`position`或`false`:

```js
if (res) {
    Geolocation.getCurrentPosition(
      async (position) => {
        setLocation(position); // 你可能不需要更新状态,或者根本不需要它
        navigation.navigate("Map", position); // 在这里不能使用"location",因为它还没有更新
      },
      async (error) => {
        // 请参考下面的错误代码表。
        console.log(error.code, error.message);
        setLocation(false); // 你可能不需要更新状态,或者根本不需要它
        navigation.navigate("Map", false); // 在这里不能使用"location",因为它还没有更新
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  } else {
    // ... 处理else情况
  }

如果需要进一步的帮助,请告诉我。

英文:

>Why does location always sets to false even though it's set to current location.

In fact it is not set to false but because it is initially false when you create it and here the navigation happens before the promise arrives so thats why.

you want to make the navigation happen insinde the .then block therefore you don't need to use the state for that just use position or false directly :

if (res) {
    Geolocation.getCurrentPosition(
      async (position) =&gt; {
        setLocation(position); // you may don&#39;t need to update the state or maybe don&#39;t need it at all
        navigation.navigate(&quot;Map&quot;, position); // you cannot use &quot;location&quot; here because it isn&#39;t updated yet
      },
      async (error) =&gt; {
        // See error code charts below.
        console.log(error.code, error.message);
        setLocation(false); // you may don&#39;t need to update the state or maybe don&#39;t need it at all
        navigation.navigate(&quot;Map&quot;, false); //you cannot use &quot;location&quot; here because it isn&#39;t updated yet
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  } else {
    // ... hanlde the else case
  }

huangapple
  • 本文由 发表于 2023年6月22日 03:49:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定