【问题标题】:meteor-reactjs: in constructor collection is emptymeteor-reactjs:在构造函数集合中为空
【发布时间】:2016-04-19 05:33:35
【问题描述】:

由于我是流星/反应的新手,我不知道如何初始化我的状态变量。

我的问题是我想得到

  1. 我通过 react-meteor-data 中的 createContainer 收集的 mongo(如 here 所述),
  2. 使用初始化的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);

【问题讨论】:

    标签: mongodb meteor reactjs ecmascript-6 meteor-react


    【解决方案1】:

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

    要捕捉这种变化,请在您的 React 组件中实现 componentWillReceiveProps 函数。

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

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

    【讨论】:

    • 感谢您的建议。我实现了 componentWillReceiveProps 函数。现在我收到带有 AllLists.find({}).fetch 结果的道具。但似乎调用函数时 fetch 尚未完成,因为数组在不同调用时具有不同的长度。
    • 您还可以查看订阅状态。 stackoverflow.com/questions/36585564/…
    • 好的,现在可以了!谢谢。不过感觉用起来不方便。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 2019-04-04
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2016-10-14
    • 2019-12-29
    相关资源
    最近更新 更多