Javascript 访问Meteor React'中的URL参数;创建容器
在我的React/Meteor应用程序中,我使用的是Javascript 访问Meteor React'中的URL参数;创建容器,javascript,mongodb,reactjs,meteor,meteor-react,Javascript,Mongodb,Reactjs,Meteor,Meteor React,在我的React/Meteor应用程序中,我使用的是React router,我试图将URL参数(示例URL:/user/p8hdqmauaapresoo6)传递到createContainer,该程序将获取第一个MongoDB查询的结果 let user = Meteor.users.findOne({ _id: this.props.params.id}); 运行第二个MongoDB查询 users: Meteor.users.find( {
React router
,我试图将URL参数(示例URL:/user/p8hdqmauaapresoo6
)传递到createContainer
,该程序将获取第一个MongoDB查询的结果
let user = Meteor.users.findOne({ _id: this.props.params.id});
运行第二个MongoDB查询
users: Meteor.users.find(
{
'location': {
$near: {
$geometry: {
'type': 'Point',
'coordinates': user.location.coordinates
...
但是,这会导致错误
Uncaught TypeError: Cannot read property 'params' of undefined
this.props.params
createContainer
内部运行第一个Mongodb查询Meteor.users.findOne()
import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
export class User extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
Something
</div>
)
}
}
export default createContainer(() => {
Meteor.subscribe('allUsers')
let user = Meteor.users.findOne({ _id: this.props.params.id});
return {
users: Meteor.users.find(
{
'location': {
$near: {
$geometry: {
'type': 'Point',
'coordinates': user.location.coordinates
},
$maxDistance: 400
}
}
}
).fetch()
}
}, User);
createContainer
接受来自react路由器(或任何父级)的道具作为函数参数。这应该起作用:
export default createContainer(({params}) => {
Meteor.subscribe('allUsers')
let user = Meteor.users.findOne({ _id: params.id});
return {
users: Meteor.users.find(
{
'location': {
$near: {
$geometry: {
'type': 'Point',
'coordinates': user.location.coordinates
},
$maxDistance: 400
}
}
}
).fetch()
}
}, User);
谢谢它的工作。我还通过修改代码更新了问题,添加了
if…else
语句,以便createContainer
在mongodb查询尚未就绪时将空道具传递给User
组件。可以吗?代码是有效的,但我不确定这是否是常见的做法
export default createContainer(({params}) => {
Meteor.subscribe('allUsers')
let user = Meteor.users.findOne({ _id: params.id});
return {
users: Meteor.users.find(
{
'location': {
$near: {
$geometry: {
'type': 'Point',
'coordinates': user.location.coordinates
},
$maxDistance: 400
}
}
}
).fetch()
}
}, User);