使用 Map 函数编写 React 组件时对象作为 React Child 无效
Objects are Not Valid as React Child when using Map Function to write React Components
我正在构建一个反应本机应用程序,它具有地图功能,可以在地图上为一系列不同的地方创建标记。为此,我使用 API 来获取坐标,因此需要使用异步函数:
<MapView style={styles.mapStyle}>
{this.state.isLoading ? null :
this.state.places.map(async (place) => {
const coords = await fetchCoords(place)
return (
<MapView.Marker
coordinate = {coords}
/>
)
})
}
</MapView>
但是这段代码给出了错误:Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72})
。我猜错误是因为我错误地实现了异步映射功能。应该是什么?
传递给 Market 组件的坐标属性需要是一个对象或数组(代表 latitude/longitude、x/y 等)但是传递的是一个承诺。
"const coords = await fetchCoords(place)" 部分不应该直接在你的渲染方法中发生,而是在其他地方像 componentDidMount 然后保存到状态,或者在更高阶的组件中进行异步调用并将结果作为道具传递.这将确保 fetchCoords 函数不会在每次重新渲染时不必要地被调用。
我正在构建一个反应本机应用程序,它具有地图功能,可以在地图上为一系列不同的地方创建标记。为此,我使用 API 来获取坐标,因此需要使用异步函数:
<MapView style={styles.mapStyle}>
{this.state.isLoading ? null :
this.state.places.map(async (place) => {
const coords = await fetchCoords(place)
return (
<MapView.Marker
coordinate = {coords}
/>
)
})
}
</MapView>
但是这段代码给出了错误:Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72})
。我猜错误是因为我错误地实现了异步映射功能。应该是什么?
传递给 Market 组件的坐标属性需要是一个对象或数组(代表 latitude/longitude、x/y 等)但是传递的是一个承诺。
"const coords = await fetchCoords(place)" 部分不应该直接在你的渲染方法中发生,而是在其他地方像 componentDidMount 然后保存到状态,或者在更高阶的组件中进行异步调用并将结果作为道具传递.这将确保 fetchCoords 函数不会在每次重新渲染时不必要地被调用。