如何处理需要子组件状态的Meteor数据

How to handle Meteor Data that requires state from child component?

本文关键字:组件 状态 数据 Meteor 何处理 处理      更新时间:2024-01-06

将Meteor 1.3中的一些代码转换为ES6+React语法。组件需要获取Meteor数据,所以我使用createComponent来替换getMeteorData()。问题是,旧的getMeteorData使用了组件中的状态,createContainer组件没有访问该状态。

旧代码:

Component = React.createClass({
   mixins: [ReactMeteorData],
   getMeteorData() {
    var mo = this.state.currentMonth;
    var start = newDate(moment(mo).startOf('month'));
    return {
     events:     collections.events.find({
        $or:       qwry,
        startDate: { $gte: start },
        endDate:   { $lte: end }
      }).fetch(),
    }
  },
  render() {
   ...
  }
});

迄今为止的新代码

class Component = React.Component {
 constructor(props) {
  super(props);
 }
 render() {
  ...
 }
}
export default createContainer(({params}) => {
var mo = this.state.currentMonth;
        var start = newDate(moment(mo).startOf('month'));
        return {
         events:     collections.events.find({
            $or:       qwry,
            startDate: { $gte: start },
            endDate:   { $lte: end }
          }).fetch(),
        }
}, Component);

获取错误"cannot get currentMonth of undefined",因为它正在尝试访问状态。有什么建议吗?

您可以将旧组件拆分为两个部分组件:一个保存状态并处理事件,另一个仅显示结果。请确保将事件处理程序作为回调传递给子组件。还要注意父组件如何使用createContainer()函数的返回值。

// Parent component, setState should go here
export default class StateHolder extends React.Component {
  constructor(params) {
    super(params);
    this.state = {myKey: 1};
  }
  incrementKey() {
    this.setState({myKey: this.state.myKey + 1});
  }
  render() {
    return <Container myKey={this.state.myKey} onClick={this.incrementKey.bind(this)} />;
  }
}
// Child component, renders only
class PureComponent extends React.Component {
  render() {
    return <div>
      {this.props.myValue}
      <button onClick={this.props.onClick}>click me</button>
    </div>;
  }
}
// Decorated child container. 
// Make sure to use this one in parent component's render() function!
let Container = createContainer((props) => {
  let doc = MyCollection.findOne({someKey: props.myKey});
  return {
    myValue: doc ? doc.someValue : null
  }
}, PureComponent);