简体   繁体   中英

Getting the value of Props parameter as undefined (ReactJS)

I'm having an attribute in one of the components and when I'm trying to access that attribute via props, I'm getting its value as undefined.

Below is the piece of code where I'm making use of the component and passing the required attribute.

import React, { Component } from "react";
import PageNotFound from "./pages/page-not-found";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import BookSectionPage from "./pages/books-section";
import BookDetails from "./pages/book-details";

class App extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
          <Switch>
            <Route path="/" exact component={BookSectionPage}/>
            <Route path="/book/category/:categoryName" exact render = { (props) => {
              return <BookSectionPage title = "JavaScript" /> // This is the component
            }} />
            <Route path="/book/:bookID" exact component={BookDetails} />
            <Route component={PageNotFound} />
          </Switch>
        </BrowserRouter>
      </div>
    );
  }
}

export default App;

Below is the code for the component where I'm trying to access the above-mentioned attribute via Props but getting its value as undefined.

import React from "react";
import Header from "../components/header/header";
import Footer from "../components/Footer/footer";
import BookSectionComponent from "../components/books-section/books-section";

const BookSectionPage = (Props) => {
  let books=[1,2,3,4,5,6];
  console.log(Props.title);     // Here instead of printing the value of attribute, it's showing undefined. 
  return (
    <div className="has-fixed-footer">
      <Header />
      <BookSectionComponent title = {Props.title} books = {books} />
      <Footer />
    </div>
  );
};

export default BookSectionPage;

Any help would be highly appreciated. Thanks!

From Parent to Child Using Props

App
└── Parent
    ├── Child1

Most easiest direction of data flow in React and basic example.

Parent Component

class Parent extends React.Component {
state = { title : "JavaScript" } 
render() {

        return (
            <div>           
                 <Child1 dataFromParent = {this.state.title} />
            </div>
        );
    }
}

Child Component

class Child1 extends React.Component {
render() {

        return (
            <div>
                The data from parent is:{this.props.dataFromParent}
            </div>
        );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM