显示来自 JSON 个对象的一对值
Display one value pair from JSON object
我会在开头说我是一名刚接触 React 的 UX 设计师。
我正在使用 Expo/React-Native 并使用 "Location" 功能来获取设备的位置信息。我可以使用 JSON 对象获取信息:
const { height, width } = Dimensions.get("window");
class Explore extends Component {
static navigationOptions = {
header: null
};
state = {
locationResult: ""
};
componentDidMount() {
this._getLocationAsync();
}
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== "granted") {
this.setState({
locationResult: "Permission to access location was denied"
});
}
let location = await Location.getCurrentPositionAsync({});
let geocode = await Location.reverseGeocodeAsync(location.coords);
this.setState({ locationResult: JSON.stringify(geocode) });
};
在我的渲染中,我使用以下方式调用该值:
<WelcomeText>
Discover {this.state.locationResult}
</WelcomeText>
哪个returns对象:
[{"street":"Stockton St","city":"San Francisco","region":"CA","country":"United States","postalCode":"94108","isoCountryCode":"US","name":"1 Stockton St"}]
但是我如何才能只显示对象中 "City" 的值?
试试这个:
<WelcomeText>
Discover {this.state.locationResult[0].city}
</WelcomeText>
解释:
您的 this.state.locationResult
是一个对象数组。使用 this.state.locationResult[0]
我们正在访问第一个对象。然后我们可以使用 .
运算符来访问我们想要的 属性 。你的情况 .city
编辑:
您需要在不对其进行字符串化的情况下传入地理编码,否则您将无法像我上面描述的那样访问它。 reverseGeocodeAsync
已经返回一个对象数组,无需将其转换为字符串。
替换:
this.setState({ locationResult: JSON.stringify(geocode) });
与:
this.setState({ locationResult: geocode });
编辑2:
这是一个工作示例:https://snack.expo.io/B1SqSd3iN
我会在开头说我是一名刚接触 React 的 UX 设计师。
我正在使用 Expo/React-Native 并使用 "Location" 功能来获取设备的位置信息。我可以使用 JSON 对象获取信息:
const { height, width } = Dimensions.get("window");
class Explore extends Component {
static navigationOptions = {
header: null
};
state = {
locationResult: ""
};
componentDidMount() {
this._getLocationAsync();
}
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== "granted") {
this.setState({
locationResult: "Permission to access location was denied"
});
}
let location = await Location.getCurrentPositionAsync({});
let geocode = await Location.reverseGeocodeAsync(location.coords);
this.setState({ locationResult: JSON.stringify(geocode) });
};
在我的渲染中,我使用以下方式调用该值:
<WelcomeText>
Discover {this.state.locationResult}
</WelcomeText>
哪个returns对象:
[{"street":"Stockton St","city":"San Francisco","region":"CA","country":"United States","postalCode":"94108","isoCountryCode":"US","name":"1 Stockton St"}]
但是我如何才能只显示对象中 "City" 的值?
试试这个:
<WelcomeText>
Discover {this.state.locationResult[0].city}
</WelcomeText>
解释:
您的 this.state.locationResult
是一个对象数组。使用 this.state.locationResult[0]
我们正在访问第一个对象。然后我们可以使用 .
运算符来访问我们想要的 属性 。你的情况 .city
编辑:
您需要在不对其进行字符串化的情况下传入地理编码,否则您将无法像我上面描述的那样访问它。 reverseGeocodeAsync
已经返回一个对象数组,无需将其转换为字符串。
替换:
this.setState({ locationResult: JSON.stringify(geocode) });
与:
this.setState({ locationResult: geocode });
编辑2:
这是一个工作示例:https://snack.expo.io/B1SqSd3iN