【问题标题】:ReactJS: Turn object into array and renderReactJS:将对象转换为数组并渲染
【发布时间】:2017-04-26 09:39:21
【问题描述】:

所以,我的组件从父组件接收一个对象,该对象如下所示:

{ 
  _id: Data.now(), // MongoDB database
  name: "",
  description: "",
  image: "images/image.jpg",
  type: "image"
}

在我的子组件中,我想获取这些数据并为每个数据进行输入,这样我就可以更改值,然后保存新数据。

更新答案(es6 类):

constructor(props) {
  super();
  this.state = {
    fieldGroups: []
  }

  this.parseProps = this.parseProps.bind(this);
}

componentWillMount() {
  this.parseProps(this.props);
}

componentWillReceiveProps(nextProps) {
  this.parseProps(nextProps);
}

parseProps(props) {
  var fieldsArray = [];
  var content = props.content;
  Object.keys(content).map((field,index) => {
    if (field === 'type') {
      let fieldObj = {};
      fieldObj.field = field;
      fieldObj.value = content[field];
      fieldObj.key   = props.content._id + field;
      fieldsArray.push(fieldObj);
    }
  });
  this.setState({
    fieldGroups: fieldsArray
  });
}

render() {
  return (
    {
      this.state.fieldGroups.map((field) => {
       if (field.field === "type") { 
         return ( html element specific to type )
       } else {
         return ( a different html element )
       }
     })
    }
  )
}

所以现在我可以在让子组件决定向用户显示哪些字段的意义上分离我的组件。谢谢 DanneManne

【问题讨论】:

  • 很难从这个不完整的例子中看出。你能展示更多关于这个组件的代码吗?是一堂课吗?您是否正确实现了构造函数? stackoverflow.com/help/mcve

标签: reactjs meteor ecmascript-6


【解决方案1】:

函数componentDidMount 顾名思义,只在组件挂载后调用一次。但是,如果父组件使用更新的属性重新渲染子组件,则子组件已经挂载并且不会再次调用该函数。

另外需要注意的是componentDidMount 的目的是如果你想查看另一个元素的offsetWidthoffsetHeight 之类的东西,但如果你没有使用DOM,那么您最好使用componentWillMount 来避免对 DOM 的额外操作,因为这通常是最耗时的部分。

您缺少的是 componentWillMountcomponentWillReceiveProps 的组合用法,这是一个每次父级重新渲染子级时都会调用的函数。

我通常采用的模式是:

  constructor(props){
    super();
    this.parseProps = this.parseProps.bind(this);
  }

  componentWillMount() {
    this.parseProps(this.props);
  }

  componentWillReceiveProps(nextProps) {
    this.parseProps(nextProps);
  }

  // === Parsing Props
  //
  //  Takes care of component specific adjustment of
  //  props that parent components does not need to
  //  know about. An example can be sorting or grouping
  //  of records.
  //
  parseProps(props) {
    this.setState({
      // key: props.key
    });
  }

因此您当前在componentDidMount 中拥有的逻辑可以移动到parseProps 函数中。

【讨论】:

  • 嘿,我得到了它的工作,我会更新答案,因为解决方案需要一些试验。另外,我可能会添加一些不必要的东西。
猜你喜欢
  • 2019-11-22
  • 2021-09-14
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 2019-05-08
  • 1970-01-01
相关资源
最近更新 更多