从子组件和父组件中的数组映射数据

时间:2019-04-03 19:44:12

标签: javascript arrays reactjs

我将数据存储在数组的data.js文件中。我在Child组件(仅数组中的第一个对象)中显示该数据。我想通过父组件中的相同数组进行映射(通过渲染<ChildComponent>)。我怎样才能做到这一点?

data.js

export default {
  accordionItems: [
    {
      id: 1,
      title: 'Why is my car not green?',
      answer: 'We ran out of green color',
    },
    {
      id: 2,
      title: 'Where have all the drivers gone?',
      answer: 'It\'s lunch time',
    },
    {
      id: 3,
      title: 'Do you have a book of complains',
      answer: 'You can write at info@mail.eu',
    },
  ],
};

子组件

import Data from './data';

class AccordionItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      question: Data.accordionItems[0], //if I remove [0], no data is rendered
    };
  }

 return (
    <div >
      <div>
        <p>{question.title}</p>
        <button>toggle</button>
      </div>
      <p>{question.answer}</p>
      <hr />
    </div>
 );

父组件

import AccordionItem from './AccordionItem';
import Data from './data';


class Accordion extends Component {
  constructor(props) {
    super(props);
    this.state = {
      accordionItems: Data.accordionItems,
    };
  }
render() {
    const { accordionItems } = this.state;
    return accordionItems.map(accordionItem => (
      <AccordionItem key={accordionItem.id} />

我想从Parent组件的'data'数组中获取所有3个对象,现在我只用第一个对象就获得了3个相同的组件。

3 个答案:

答案 0 :(得分:3)

以道具的形式传递物品

struct-type

您可以在render()方法中访问它:

 <AccordionItem question={accordionItem} ... />

您根本不应该使用状态。

答案 1 :(得分:2)

您可以简单地通过map函数本身传递数据,例如:

accordionItems.map(accordionItem => (
      <AccordionItem
        key={accordionItem.id}
        open={[`isOpen-${accordionItems.id}`]}
        data={accordionItem}
      />
));

在孩子里:

class AccordionItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      question: props.data, //data from map function in parent
    };
  }

答案 2 :(得分:0)

也许您应该在React中阅读有关components and passing props的更多信息。

您可以执行以下操作,而不是将Data导入AccordionItem组件中,而是通过props将其传递给AccordionItem

这看起来像这样:

import AccordionItem from './AccordionItem';
import Data from './data';


class Accordion extends Component {
  constructor(props) {
    super(props);
    this.state = {
      accordionItems: Data.accordionItems,
    };
  }

  render() {
    const { accordionItems } = this.state;
    return accordionItems.map(accordionItem => (
        <AccordionItem
          key={accordionItem.id}
          item={accordionItem}
          open={[`isOpen-${accordionItems.id}`]}
        />
    ))
  }

现在,该项目应该可以通过子组件中的道具进行访问:

 class AccordionItem extends Component {

   render(){
     const { question } = this.props
     return (
       <div >
         <div>
           <p>{question.title}</p>
           <button>toggle</button>
         </div>
         <p>{question.answer}</p>
         <hr />
       </div>
     );
   }