我正在使用 Mongo/Meteor 1.3/React。在我的简单示例中,我使用包装器 React 组件来查询 Mongo 集合并创建一个数组。当传递给子组件时,调用构造函数时数组对象似乎尚未准备好 - 这意味着我无法访问 Prop 。
感觉这一定是一个常见问题。我应该使用不同的 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);
最佳答案
您应该使用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 中使用。
关于javascript - 如何传递数组并在 React Lifecycle 中访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39850420/