简体   繁体   中英

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.

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:

<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.

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 }} /> } />

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