【问题标题】:Getting the value of Props parameter as undefined (ReactJS)将 Props 参数的值设为未定义(ReactJS)
【发布时间】:2020-06-13 21:16:26
【问题描述】:

我在其中一个组件中有一个属性,当我尝试通过道具访问该属性时,我将其值设为未定义。

下面是我使用组件并传递所需属性的一段代码。

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;

下面是我试图通过 Props 访问上述属性但将其值设为未定义的组件的代码。

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;

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 试试这个。 const title = {name: "sometitle"},然后是
  • 您在哪个阶段将 prop title 传递给 BookSectionPage
  • @LogeshP 试过了,可惜没有成功。
  • @DennisVash 我上面给出的第一段代码是将属性传递给组件的地方(我写了一些注释供参考),然后第二段代码是我试图通过 Props 访问属性的组件的代码。
  • 尝试删除主组件中的道具

标签: javascript html reactjs web web-frontend


【解决方案1】:

使用道具从父级到子级

App
└── Parent
    ├── Child1

React 中最简单的数据流方向和基本示例。

父组件

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

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

子组件

class Child1 extends React.Component {
render() {

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

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 2018-08-06
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    相关资源
    最近更新 更多