3

Due to the fact that I am new in meteor/react I can't figure out how to initialize my state variable.

My problem is that I would like to get

  1. my mongo collection through the createContainer from react-meteor-data (as described here),
  2. use the initialized prop to intialize the state variable

But the prop in the constructor is empty. Only when I the "gotClicked" function is called the prop.allLists is filled with the data from mongo.

Does anyone know why? My guess the data is loaded asynchronously, so that the data is not available yet in the constructor. What would be a better way to get the data?

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);
4

1 回答 1

2

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

为了捕捉这个变化,componentWillReceiveProps在你的 React 组件中实现这个函数。

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

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

于 2016-04-18T21:33:35.583 回答