简体   繁体   中英

React router dom passing data from parent component to child router component does not pass the props.match

Content of the parent component App.js:-

import React, { useEffect, useState } from "react";
import NavBar from "./components/NavBar";
import Signup from "./pages/Signup";
import Home from "./pages/Home";
import Book from "./pages/Book";

function App() {
  const [user, setUser] = useState();
  useEffect(() => {
    const token = "Bearer " + sessionStorage.getItem("token");
    if (token) {
      axios
        .get(process.env.REACT_APP_API_URL + "user/self", {
          headers: {
            Authorization: token,
            "Content-Type": "application/json",
          },
        })
        .then((res) => setUser(res.data));
    }
  }, []);

  return (
    <div className="container-fluid">
      <NavBar user={user} />
      <Route exact path="/" component={Home} />
      <Route path="/signup" component={Signup} />
      <Route exact path="/book/:id" component={() => <Book user={user} />} />
    </div>
  );
}

export default App;

For the route:-

<Route exact path="/book/:id" component={() => <Book user={user} />} />

when i set the component value from component={Book} to component={() => i got an error:-

TypeError: Cannot read property 'params' of undefined

That is because i am using "props.match.params.id" inside the Book component.

How can i pass user state with props.match to he Book component?

This is how you use the component prop

<Route exact path="/book/:id" component={Book} />

consider using the render prop instead of the component prop like this:

<Route exact path="/book/:id" render={(routeProps) => <Book user={user} {...routeProps} />} />

component prop isn't a function. Use render instead of component prop.

render prop is a function to which router props object is passed as an argument. You can pass these router props to your component.

<Route exact path="/book/:id" render={(props) => <Book user={user} {...props} />} />

See react router docs for details on render prop

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