当前位置: 首页 > 面试题库 >

如何处理需要子组件状态的流星数据?

亢嘉茂
2023-03-14
问题内容

将Meteor 1.3中的某些代码切换为ES6 +
React语法。组件需要获取流星数据,因此我正在使用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);

由于尝试访问状态,因此出现错误“无法获取undefined的currentMonth”。有什么建议?


问题答案:

您可以将旧组件分为两个部分:一个包含状态并处理事件的部分,另一个仅显示结果的部分。确保将事件处理程序作为回调传递给子组件。还要注意父组件如何使用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);


 类似资料:
  • 我用React构建了3个组件。他们是: 包装器 列表 列表项 如何管理单击的复选框的状态。我想Wrapper知道哪些复选框被选中。

  • 我需要使用父组件中子组件内部的状态值。 组成部分: 这是父组件:

  • 在这个例子中,我想在我的父组件中使用我的子组件的状态。

  • 我正在将父组件的状态从父组件传递到子组件。在子组件中,我有一个不同的状态。我正在对子组件的状态执行一些操作,并且结果必须添加到父组件的状态。因此,在我的父组件中,我编写了一个回调函数,该函数将更新父组件的状态。代码为: 因此,这个函数随后作为道具传递给子组件: 然后在我的子组件中,我试图实现回调函数为: 但这并没有达到预期效果。这是正确的方法吗?有人能帮我吗? 我试图通过实现这里提供的解决方案来解

  • 如何在自定义钩子中创建组件,钩子保存组件的状态? 我的尝试基本上是正确的,但是拖放并没有像预期的那样工作。相反,滑块只会在单击时更改值。我认为问题在于,useState钩子在定义之外被调用。但是我们如何在钩子中创建一个组件,然后我需要在钩子的其余部分中处理该内部组件的状态? https://codesandbox.io/s/material-demo-milu3?file=/demo.js:0-3

  • 问题内容: 所以,我有多个ReactComponent。最初,我以为会有一个带有其自身状态的父组件(简称为GrandPa),它将有关其状态的一些信息传递给另一个组件(称为Parent)。同样,父母将他的一些财产传给孩子,孩子则传给孙子。因此,我们具有层次结构: 爷爷->父母->孩子->孙子 但是,我很快意识到,当我使用method 更改GrandPa的状态时,所做的更改不会沿通道向下级联。我意识到