将道具传递到PrivateRoute组件

时间:2020-11-01 19:37:18

标签: reactjs gatsby

嗨,我有一个react(GatsbyJs)应用程序,我在这里使用动态获取的数据和身份验证。我有一个PrivateRoute组件,该组件检查用户是否已登录,然后根据状态重定向到该组件或登录页面。 我现在需要将道具传递给组件,但无法掌握。

这是PrivateRouter:

import React from 'react'
import { navigate } from 'gatsby'
import { isLoggedIn } from '../services/auth'

const PrivateRoute = ({ component: Component, location, ...rest }) => {
  if (!isLoggedIn() && location.pathname !== '/app/login') {
    navigate('/app/login')
    return null
  }
  return <Component {...rest} />
}

export default PrivateRoute

和app.js代码:

import React from "react"
import { Router } from "@reach/router"
import Layout from "../components/layout"
import OrderDetails from "../modules/order-details"
import ItemDetails from "../modules/item-details"
import ProductionOrders from "../modules/production-orders"
import ProdOrderDetail from "../modules/production-order-detail"
import CardDetail from '../modules/card-details'
import Cards from "../modules/cards"
import Orders from "../modules/orders"
import Items from "../modules/items"
import PrivateRoute from '../components/privateRoute'
import Profile from '../components/profile'
import Login from '../modules/login'
import ForgotPassword from "../modules/forgotPassword"
import NewPassword from "../modules/newPassword"
import Invoices from "../modules/invoices"
import Dispatches from "../modules/dispatches"
import InvoiceDetails from "../modules/invoice-details"
import OrderPlan from "../modules/order-plan"
import AccountStatementPage from "../modules/acc-statement"




const App = () => {

  return (
    <Layout>
      <Router basepath="/app">
        <PrivateRoute path="/order-details/:orderId" component={OrderDetails} />
        <PrivateRoute path="/item-details/:itemId" component={ItemDetails} />
        <PrivateRoute path='/production-orders' component={ProductionOrders} />
        <PrivateRoute path="/production-order-detail/:companyNr/:orderId" component={ProdOrderDetail} />
        <PrivateRoute path="/cards" component={Cards} />
        <PrivateRoute path="/card-details/:cardId" component={CardDetail} />
        <PrivateRoute path="/orders" component={Orders} />
        <PrivateRoute path="orders/cId/:cId" component={Orders} />
        <PrivateRoute path="orders/keyword/:keyword" component={Orders} />
        <PrivateRoute path="/items" component={Items} />
        <PrivateRoute path="/items/keyword/:keyword" component={Items} />
        <Login path="/login" />
        <ForgotPassword path="/forgot-password" />
        <NewPassword path="/new-password" />
        <PrivateRoute path="/profile" component={Profile} />
        <PrivateRoute path="/invoices/" component={Invoices}/>
        <PrivateRoute path="/invoices/cId/:cId" component={Invoices}/>
        <PrivateRoute path="/dispatches/" component={Dispatches}/>
        <PrivateRoute path="/dispatches/cId/:cId" component={Dispatches}/>
        <PrivateRoute path="/invoice-details/:invId" component={InvoiceDetails} />
        <PrivateRoute path="/order-plan" component={OrderPlan} />
        <PrivateRoute path="/acc-statement/:id" component={AccountStatementPage}/>
      </Router>
    </Layout>
  )
}
export default App

我应该如何重新加工它们以便将道具传递给组件?

谢谢。

P.S。

这是组件:

import React from 'react'
import Container from "react-bootstrap/Container"
import Col from 'react-bootstrap/Col'
import Row from 'react-bootstrap/Row'
import AccStatement from '../components/accStatement'



const AccountStatementPage = (props,{location}) => {
console.log(location)
console.log(props)

    return (

        <Container fluid>
            <h1>Cari Hesap Ekstresi</h1>
            <Row className="h-100">
                
            
                        <AccStatement id={props.id} />
               
                
            </Row>
        </Container>
    )
}
export default AccountStatementPage

3 个答案:

答案 0 :(得分:1)

您的私人路线组件已经配置为将任何附加道具从路由器传递到 ,但是由于您试图将其他数据发送到渲染的组件您需要正确发送路由状态。

Link

<Link to=“...” myState=“....” >

您可以从传递给每个渲染组件的location道具中访问路线状态。

const MyComponent = ({ location }) => {
  return (
    <div>My route state: {location.state.myState}</div>
  );
};

如果您的组件未收到路线道具,则可以使用useLocation react钩子。

const MyComponent = () => {
  const location = useLocation();

  return (
    <div>My route state: {location.state.myState}</div>
  );
};

我应该如何在目标组件中访问它?

location应该注入到props传递给组件的Route对象中。这不是一个单独的论点。路线参数也放置在match道具上,而不是根级别的道具值。

给予

<PrivateRoute
  path="/acc-statement/:id"
  component={AccountStatementPage}
/>

组件

const AccountStatementPage = ({ location, match }) => {
  useEffect(() => {
    // Log route state and match param `id` on mount
    console.log(location.state, match.id);
  }, []);

  return (
    <Container fluid>
      <h1>Cari Hesap Ekstresi</h1>
      <Row className="h-100">
        <AccStatement id={match.id} />
      </Row>
    </Container>
  )
};

答案 1 :(得分:0)

PrivateRoute组件中,您将component分解为Component(进行渲染),location和其余(...restprops的其余部分。

要将自定义道具传递到PrivateRoute内的组件,只需直接访问prop

在您的app.js中:

    <PrivateRoute path="/order-plan" component={OrderPlan} customProp={`hello`}/>

您的customProp通过rest中的PrivateRoute传播算子传递到您的组件,因此,在您的组件中,只需访问props.customProp

如果您想使用Link组件传递某些内容,则应使用Gatsby Link本身提供的状态(因为Gatsby从@reach/router扩展而来):

<Link
  to={`/order-plan`}
  state={{ yourVariable: 'hello' }}
>

然后,您必须在order-plan页上访问props.location.state.yourVariable才能获取数据。

答案 2 :(得分:0)

我无法通过位置访问路线状态。一直都是不确定的。 但是我可以通过以下方式访问路由状态:

window.history.state.customProps

谢谢您的支持。