简体   繁体   English

反应路由器将道具传递给子组件

[英]React router Passing props to a child component

This is the Apps server that is supplies the functionality of the React Router - It functions as I expect.这是提供 React Router 功能的 Apps 服务器 - 它按我的预期运行。

import React, { Component } from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import NavTabs from "./components/NavTabs";
import Home from "./components/pages/Home";
import Search from "./components/pages/Search";
import Saved from "./components/pages/Saved";
import Contact from "./components/pages/Contact";
import API from "./utils/API";

class App extends Component {
  // Setting our component's initial state
  state = {
    books: [],
    title: "",
    author: "",
    synopsis: ""
  };

  // When the component mounts, load all books and save them to this.state.books
  componentDidMount() {
    this.loadBooks();
  }

  // Loads all books  and sets them to this.state.books
  loadBooks = () => {
    API.getBooks()
      .then(res =>
        this.setState({ books: res.data, title: "", author: "", synopsis: "" })
      )
      .catch(err => console.log(err));
  };

  // Deletes a book from the database with a given id, then reloads books from the db
  deleteBook = id => {
    API.deleteBook(id)
      .then(res => this.loadBooks())
      .catch(err => console.log(err));
  };

  // Handles updating component state when the user types into the input field
  handleInputChange = event => {
    const { name, value } = event.target;
    this.setState({
      [name]: value
    });
  };


  render() {
    return (
      <Router>
        <div>
          <NavTabs />
          <Route exact path="/" component={Search} />
          <Route exact path="/search" component={Search} />
          <Route exact path="/saved" render={(props) => <Saved {...props} />} />
          <Route path="/contact" component={Contact} />
        </div>
      </Router>
    );
  }
}

export default App;

The component Saved I'm trying to pass the props too.已保存的组件我也在尝试传递道具。

import React from "react";
import { Col, Row, Container } from "../../components/Grid";
import { List, ListItem } from "../../components/List";



function Saved(props) {
  return (
    <div>
      <h1>Saved</h1>
      <Col size="md-6 sm-12">
            {this.state.books.length ? (
              <List>
                {this.state.books.map(book => {
                  return (
                    <ListItem key={book._id}>
                      <a href={"/books/" + book._id}>
                        <strong>
                          {book.title} by {book.author}
                        </strong>
                      </a>
                    </ListItem>
                  );
                })}
              </List>
            ) : (
              <h3>No Results to Display</h3>
            )}
          </Col>
    </div>
  );
}

export default Saved;

The error I get is我得到的错误是

TypeError: Cannot read property 'state' of undefined
Saved
C:/class/googlebooks/googlebooks/client/src/components/pages/Saved.js:11
   8 | return (
   9 |   <div>
  10 |     <h1>Saved</h1>
> 11 |     <Col size="md-6 sm-12">
     | ^  12 |           {this.state.books.length ? (
  13 |             <List>
  14 |               {this.state.books.map(book => {

Any help is appreciated , Is it a context issue?任何帮助表示赞赏,这是上下文问题吗? I'm new to react so, yea some of the code is rough\\snipped.我是新手,所以有些代码很粗糙\\剪断了。 I'm trying to learn the concept.我正在努力学习这个概念。

In the main app you want to pass the whole state to child component as prop so you do it this way:在主应用程序中,您希望将整个状态作为 prop 传递给子组件,因此您可以这样做:

<Route exact path="/saved" render={ () => <Saved data = { this.state } />} />

Inside the child components you access the props as parameters and from there you access data object (you just passed in the main component at route } which contains the whole state.在子组件中,您将 props 作为参数访问,然后从那里访问数据对象(您刚刚在 route 处传入了包含整个 state 的主组件)。

function Saved(props) {
  return(
       props.books.map(); // you have access at books array
    )

}
function Saved ({ books }) { 
     // Use books array
}

In App应用内

...
<Route exact path="/saved" render={ () => <Saved {{ books: this.state.books }} /> } />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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