Невозможно отобразить Компонент, передающий состояние React в реквизиты для другого Компонента. - PullRequest
2 голосов
/ 23 сентября 2019

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

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

Я попытался передать состояние в главном компоненте, который вызывает файл "Desc.js", чтобы получить информацию, отправленную как реквизиты компоненту функции Home, который, в свою очередь, отправляетэто подставляется как переменная {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 никогда не отображается.Помогите пожалуйста

Ответы [ 2 ]

1 голос
/ 23 сентября 2019

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

<RenderDesc item={props.content}/>

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

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

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

0 голосов
/ 23 сентября 2019

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


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>
);
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...