【问题标题】:React router Passing props to a child component反应路由器将道具传递给子组件
【发布时间】:2020-03-26 13:54:26
【问题描述】:

这是提供 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 => {

感谢任何帮助,这是上下文问题吗?我是新来的反应,是的,有些代码是粗糙的\被剪断的。我正在努力学习这个概念。

【问题讨论】:

  • 您在功能组件中使用this.state。你正在传递道具,所以你应该参考props。不需要this 字,因为Saved 不是基于类的组件。
  • 另外,您需要将this.state 传递给Saved 组件。
  • Samet M。你搞定了,甚至在我问之前回答了后续问题。

标签: reactjs react-router react-props


【解决方案1】:
function Saved ({ books }) { 
     // Use books array
}

应用内

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

【讨论】:

    【解决方案2】:

    在主应用程序中,您希望将整个状态作为道具传递给子组件,因此您可以这样做:

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

    在子组件中,您可以将 props 作为参数访问,然后从那里访问数据对象(您只需在包含整个状态的 route } 处传入主组件。

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

    【讨论】:

      猜你喜欢
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 2019-08-15
      • 2018-08-22
      • 2017-10-01
      • 2017-03-19
      相关资源
      最近更新 更多