【问题标题】:How to pass an Array and access it within React Lifecycle如何传递一个数组并在 React 生命周期中访问它
【发布时间】:2016-10-04 19:46:21
【问题描述】:

我正在使用 Mongo/Meteor 1.3/React。在我的简单示例中,我使用包装器 React 组件来查询 Mongo 集合并创建一个数组。传递给 Child 组件时,调用构造函数时似乎 Array 对象尚未准备好 - 这意味着我无法访问道具。

感觉这一定是一个普遍的问题。我应该使用不同的 React 生命周期组件吗?或者添加某种形式的 waitOn 函数?任何建议表示赞赏!

父组件

export default class BulkMapWrapper extends TrackerReact(React.Component) {

constructor() {
super();
const subscription =  Meteor.subscribe("listing",{sort: {_id:-1}})
this.state = {
eventsData: subscription
}
}


render () {
var markerArray = []
markerArray = ...


return(
<div className="panel panel-default">
<div className="panel-body">
<FourthMap
mapParams = {manyEvents}
markers = {markerArray}
 />
</div>
</div>
)

子组件

export default class GooleMapComponent extends Component {
constructor(props){
super(props)
console.log(this.props.markers);

【问题讨论】:

  • 这一行 Meteor.subscribe("listing",{sort: {_id:-1}}) 是异步的吗?
  • 我相信这不是异步的,我通过添加以下行来测试它 this.state = { ready: subscription.ready(), eventsData: subscription } 。 this.state.ready 仍然为 false,尽管我可以从控制台查询集合...

标签: javascript arrays mongodb reactjs meteor


【解决方案1】:

您应该使用componentDidMount 函数获取数据,然后使用结果数据设置新状态。

class GetData extends React.Component {
  constructor(props) {
   super(props);
   this.state = {};
  }

  componentDidMount() {
     const subscription =  Meteor.subscribe("listing",{sort: {_id:-1}});

     this.setState({
       eventsData: subscription
     });
  }
}

然后,您可以将状态从 GetData 组件作为 props 传递给它的子组件,或显式传递给 render 函数中的另一个组件。

这通常是您在 React 中处理 AJAX 请求的方式,但我不确定这是否能很好地转化为在 Meteor 中使用。

【讨论】:

猜你喜欢
  • 2021-06-18
  • 2017-11-04
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 2021-03-20
  • 2019-03-28
  • 2010-10-04
相关资源
最近更新 更多