React Router将道具传递给子组件

时间:2019-12-01 22:43:57

标签: reactjs react-router react-props

这是提供了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;

已保存的组件我也在尝试传递道具。

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;

我得到的错误是

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 => {

感谢您的帮助,这是一个上下文问题吗?我是新来的人,所以,是的,某些代码很粗\。我正在尝试学习这个概念。

2 个答案:

答案 0 :(得分:0)

在主应用中,您要将整个状态作为prop传递给子组件,因此您可以这样做:

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

在子组件内部,您可以访问props作为参数,然后从那里访问数据对象(您刚刚在主组件中传递了路径},其中包含了整个状态。

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

}

答案 1 :(得分:0)

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

应用内

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