简体   繁体   English

React路由器dom将数据从父组件传递到子路由器组件不传递props.match

[英]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:-父组件 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:-当我将组件值从 component={Book} 设置为 component={() => 我得到一个错误:-

TypeError: Cannot read property 'params' of undefined TypeError:无法读取未定义的属性“参数”

That is because i am using "props.match.params.id" inside the Book component.那是因为我在 Book 组件中使用了“props.match.params.id”。

How can i pass user state with props.match to he Book component?如何将带有 props.match 的用户 state 传递给他的 Book 组件?

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:考虑使用render prop 而不是component prop,如下所示:

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

component prop isn't a function. component道具不是 function。 Use render instead of component prop.使用render而不是component道具。

render prop is a function to which router props object is passed as an argument. render道具是一个 function 路由器道具 object 作为参数传递给它。 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有关render道具的详细信息,请参阅反应路由器文档

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

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