Не удается отобразить компонент, передающий состояние React реквизитам для другого компонента

У меня была довольно простая проблема, и все предыдущие вопросы, которые я читал, касались более сложных проблем, поэтому я публикую их, надеясь, что кто-нибудь поможет мне с этим.

У меня есть основной компонент, в котором я вызываю все остальные компоненты в своем приложении, чтобы отображать их в App.js. Внутри этого основного компонента у меня есть компонент домашней функции, который отображает домашнюю страницу. Мне не удается отобразить функциональные компоненты внутри домашнего компонента. Я представляю свой код по порядку.

Я попытался передать состояние в основной компонент, который вызывает файл «Desc.js» для получения информации, отправленной в качестве реквизита в компонент домашней функции, который, в свою очередь, отправляет этот реквизит в виде переменной {item} функциональному компоненту RenderDesc.

это App.js

import React, { Component } from 'react';
import Main from './components/MainComponent';
import './App.css';
import { BrowserRouter } from 'react-router-dom';

class App extends Component {
  render(){
    return (
      <BrowserRouter>
        <div>
          <Main />
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

Это MainComponent.js

import React, { Component } from 'react';
import Header from './include/HeaderComponent';
import Footer from './include/FooterComponent';
import Home from './HomeComponent';
import Login from './LoginComponent';
import {DESC} from '../shared/Desc.js';
import {Switch, Route, Redirect} from 'react-router-dom';

class Main extends Component {
  constructor(props){
    super(props);
    this.state={
      contents: DESC
    }
  }
  render(){
    const HomePage = () => {
      return(
        <Home content = {this.state.contents}
        />
      );
    }
    return(
      <div>
        <Header />
        <div className="container">
          <Switch>
            <Route path = "/home" component = {HomePage} />
            <Route exact path = '/login' component = {Login} />
            <Redirect to = "/home"></Redirect>
          </Switch>
        </div>
        <Footer />
      </div>
    );
  }
}

export default Main;

Это HomeComponent.js

import React from 'react';

function RenderDesc({item}){

        return(
            <div id={item.desc_id} className="row row-content align-items-center">
                <div className="col-12 col-sm-4 col-md-3">
                    <img src={item.desc_image} className="img-ex img-fluid" alt={item.desc_image_alt}/>
                </div>
                <div className="col col-sm col-md">
                    <p>{item.desc_content1}</p>
                    <p>{item.desc_content2}</p>
                </div>
            </div>
        );
}

function Home(props){
    return(
        <div className="container">
            <div className="cover-container mx-auto flex-column">
                    <div className="inner cover text-center">
                    <h1 className="cover-heading">Data to take <br />Control</h1>
                    <p className="lead">We create the efficient and effective solution
                        your organization needs to act informed and on time.</p>
                    <p className="lead">
                        <a href="#about" className="btn btn-lg btn-secondary">Find out more</a>
                    </p>
                </div>
            </div>
            <RenderDesc item={props.content}/>
        </div>
    );
}

export default Home;

А это содержимое Desc.js

export const DESC=
[
  {
    desc_id: 1,
    desc_content1: 'As time passes, the accumulation of spreadsheets and even shared documents to manage the operation of your business in a daily basis, becomes complicated and slow down common tasks. This can significantly impact your team’s performance.',
    desc_content2: 'We develop personalized implementations to respond our customer’s needs. We aim to integral solutions that scans the processes, identify the main features and smooth the user interface with friendly tools, easy to manage.',
    desc_image: 'images/icons/phone.png',
    desc_image_alt: 'phone',
  },
  {
    desc_id: 2,
    desc_content1: 'Take the step to a real virtualization and automation of your processes can be challenging, moreover when is desired to avoid any disruption. Although, to hold competitivenes and increase efficiency, is an issue that must be addressed. When is possible, graduality is an effective strategy.',
    desc_content2: 'We develope solutions that adapts to requirements, printing on back-end and front-end developments, ease and simplicity that enables a smooth adaptation of the team. This creates trust and helps to draw their attention from the repetitive and lateral tasks, towards the operations that requires the professional’s criteria and flexibility.',
    desc_image: 'images/icons/mind.png',
    desc_image_alt: 'mind',
  }
]

Но, в конце концов, содержимое Desc.js никогда не отображается. Помогите, пожалуйста


person Alonso Rodriguez    schedule 23.09.2019    source источник
comment
материал в DESC представляет собой массив объектов. вы пытаетесь получить только один элемент из массива? или вы ожидаете, что список элементов будет отображаться?   -  person azium    schedule 23.09.2019


Ответы (2)


Привет. Ваш контент [] из {}. Вы должны отобразить его и повторить.


function RenderDesc({items}){

return(
   items.map(item=>(<div id={item.desc_id} className="row row-content align-items-center">
   <div className="col-12 col-sm-4 col-md-3">
       <img src={item.desc_image} className="img-ex img-fluid" alt=    {item.desc_image_alt}/>
   </div>
   <div className="col col-sm col-md">
       <p>{item.desc_content1}</p>
       <p>{item.desc_content2}</p>
   </div>
</div>))
);
}

function Home(props){
return(
   <div className="container">
       <div className="cover-container mx-auto flex-column">
               <div className="inner cover text-center">
               <h1 className="cover-heading">Data to take <br />Control</h1>
               <p className="lead">We create the efficient and effective solution
                   your organization needs to act informed and on time.</p>
               <p className="lead">
                   <a href="#about" className="btn btn-lg btn-secondary">Find out more</a>
               </p>
           </div>
       </div>
       <RenderDesc items={props.content}/>
   </div>
);
}

person Lesha Petrov    schedule 23.09.2019
comment
Благодарность! Я пытался повторять, но я думаю, что мой код был слишком ошибочным. Ваш работает идеально! - person Alonso Rodriguez; 23.09.2019

DESC - это массив. Тем не менее, вы, кажется, пытаетесь представить его, как если бы это был один объект. Попробуйте изменить...

<RenderDesc item={props.content}/>

в компоненте Home к...

{props.content.map(item => <RenderDesc key={item.desc_id} item={item}/>)}

Это отобразит один RenderDesc для каждого объекта в массиве DESC.

person Charlie Martin    schedule 23.09.2019