我确信这一定是一个相当常见的问题,但我在 Stack Overflow 上找不到一个好的最新解决方案......在 React/Meteor 领域内。我想查询 mongoDB 以提取一些信息,然后将其传递到我的 react 组件状态中。目前我正在使用父组件查询 mongodb 并将其作为 props 传递给子组件 - 但是当子组件渲染时 mongoDB 调用尚未返回,因此我的 props 未定义。
从各种来源来看,我似乎需要实现对 mongo 的异步 javascript 调用,然后回调到状态。但是我在野外找不到任何这样的例子。有人有这方面的模式吗?最后 - 如果我以错误的方式处理这个问题,请加入。
任何建议表示赞赏!
export default class GooleMapComponent extends Component {
constructor(props){
super(props)
this.state = {
{position: {lat: this.props.mapParams.longitude, lng: this.props.mapParams.longitude},
// this returns undefined a
key: `goshi`,
defaultAnimation: 2
}
最佳答案
假设父组件工作正常,在我看来你有两个选择:
您可以让父组件在没有 props 时不渲染子组件
您可以让子组件工作,但在没有正确的 props 时显示“正在加载”状态
实现1:
在您的父组件上定义一个名为 renderGoogleMapComponent(mapParams)
的方法(顺便说一句,您那里有一个拼写错误,Goole
)
仅当定义了 mapParams 时才会渲染子项:
renderGoogleMapComponent(mapParams){
if(mapParams != undefined){
return <GoogleMapComponent mapParams={mapParams}/>
}
然后在父组件的render
中调用
renderGoogleMapComponent(whereverYouGetThoseMapParamsMaybe this.state.mapParams?)
你曾经去过的地方
<GoogleMapComponent mapParams={whereverYouGetThoseMapParamsMaybe this.state.mapParams?}/>
实现2:
在子组件的 render 方法中,检查是否获取了 props:
render(){
if(this.props.mapParams != undefined){
//your render logic here
} else {
return <div>Loading map data</div>
}
注意:不需要在状态中存储 Prop ,为什么要这样做呢?
另外:在构造函数中 this.props
未定义,只需使用 props
在1中,您还可以让父组件进行“加载”显示,但这是一个不同的问题,您显然应该调整它以最好地为用户服务
关于javascript - 如何通过异步 Mongo 调用设置 React State?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40128368/