Meteor-ReactJS:在构造函数中集合为空。

3
由于我对meteor/react还不熟悉,因此无法确定如何初始化我的状态变量。
我的问题在于:
1. 我想通过react-meteor-data中的createContainer获取我的mongo集合(如文档所述)。 2. 使用initialized prop来初始化状态变量。
但是,在构造函数中prop为空。只有当"gotClicked"函数被调用时,prop.allLists才会填充来自mongo的数据。
有人知道原因吗?我猜测数据是异步加载的,因此在构造函数中数据尚不可用。
如何更好地获取数据?
import React, {Component, PropTypes} from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import {AllLists} from '../api/alllists.js'
export default class MyList extends Component {

    constructor(props) {
        super();

        console.log(props.allLists)
        console.log(this.props.allLists)
        //allLists is empty

        this.state = {
            lists: props.allLists
        }
    }

    gotClicked(){
        console.log(this.props.allLists)
        //allLists is filled
    }

    render() {
        return (
            <div className="container" onClick={this.gotClicked.bind(this)}>
            </div>
        );
    }
}

MyList.propTypes = {
   allLists: PropTypes.string.isRequired
}

export default createContainer(() => {
    return {
        allLists: AllLists.find({}).fetch()
    };
}, MyList);
1个回答

2

您说得对,数据是异步加载的,可能在构造函数中不可用。但是,当数据加载时,您传递给createContainer的回调函数会再次评估,并自动更新组件的props

为了捕获这种变化,请在React组件中实现componentWillReceiveProps函数。

componentWillReceiveProps(nextProps) {
  this.setState({
    lists: nextProps.allLists
  });
}

文档在这里:https://facebook.github.io/react/docs/component-specs.html

该文档介绍了React组件规范,包括组件的生命周期、状态和属性等方面的内容。如果您想深入了解React技术,建议仔细阅读该文档。

谢谢你的建议。 我已经实现了componentWillReceiveProps函数。现在我使用AllLists.find({}).fetch来接收props的结果。但是似乎当调用该函数时,fetch还没有完成,因为不同的调用具有不同的数组长度。 - JGM
您还可以检查订阅的状态。http://stackoverflow.com/questions/36585564/conditional-rendering-in-meteor-react/36585830#36585830 - aedm
好的,现在它可以工作了!谢谢。 虽然使用起来感觉有些不方便。 - JGM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接