React BrowserRouter:位置未定义

Posted

技术标签:

【中文标题】React BrowserRouter:位置未定义【英文标题】:React BrowserRouter: Location is undefined 【发布时间】:2021-11-12 23:43:48 【问题描述】:

我正在尝试使用位置中的状态将对象从一个组件传递到另一个组件,但是,每次我尝试读取它写入给我的状态属性时,该位置是未定义的。

这是我的 App.tsx

import React,  Component  from "react";
import BrowserRouter as Router, Redirect, Route from 'react-router-dom';

import AdminPanel from "./components/admin-panel/admin-panel";
import UserPanel from "./components/user-panel/user-panel";
import OrderForm from "./components/order-form/order-form";
import Login from "./components/login/login";
import OrderSummary from "./components/order-summary/order-summary";
import Header from "./components/header/header";
import UserService from "./services/user-service";
import LoginData from "./types/types";

export default class App extends Component 

    //User data information object creation
    userService = new UserService()

    state = 
        isAuthorised: false
    

    //userService.login() execution if succeed change isAuthorised state on true
    login = async (data: LoginData) => 
        if (await this.userService.login(data)) 
            this.setState(
                isAuthorised: true
            )
        
    

    render() 
        const isAuthorised = this.state
        const userData = this.userService
        const role, name = userData

        return (
            <div>
                <Header isAuthorised=isAuthorised name=name/>
                <Router>
                    
                        !isAuthorised && (<Redirect to='/' />)
                    
                    <Route path="/" render=() => (
                        <Login login=this.login isAuthorised=isAuthorised role=role/>
                    ) exact/>
                    <Route path="/admin-panel" component=AdminPanel exact/>
                    <Route path="/user-panel" render=() => (
                        <UserPanel isAuthorised=isAuthorised userData=userData />
                    ) exact/>
                    <Route path="/order-form" render=() => (
                        <OrderForm ...userData />
                    ) exact/>
                    <Route path="/order-summary" component=OrderSummary exact/>
                </Router>
            </div>
        );
    

这是我传递数据的组件:

import React, useState from "react";
import Link from "react-router-dom";
import DefaultValues from "react-hook-form";
import FormValues from "../../../types/types";

type AccordeonItem = 
    title: string,
    data: DefaultValues<FormValues>


export const AccordeonItem = ( title, data : AccordeonItem) => 
 
    return (
       <div className="p-4 pt-0">
          <p className="text-gray-700">Some text</p>
          <Link to= pathname: '/order-form', state:  savedOrder: data >
             Reorder
          </Link>
       </div>
    );
;

最后,应该接收数据的组件:

import React from "react";
import OrderFormElements from "../parts/form-elements/order-form-elements";
import FormValues, UserData from "../../types/types";
import CalculatorService from "../../services/calculator-service";
import RouteComponentProps, withRouter from "react-router-dom";
import  StaticContext  from 'react-router';
import DefaultValues from "react-hook-form";

type LocationState = 
    savedOrder: DefaultValues<FormValues>



const OrderForm: React.FunctionComponent<UserData & RouteComponentProps<, StaticContext, LocationState>> = (userData: UserData, location: RouteComponentProps<, StaticContext, LocationState>) =>  

    const onSubmit = (data: FormValues) => 
        const Calculator = new CalculatorService(userData)
        console.log("Works",data)
    

    return <OrderFormElements 
                mail=userData.mail 
                savedOrderData=location.state.savedOrder 
                onSubmit=onSubmit />


export default withRouter(OrderForm)

正如我之前所说,在这里我收到一个位置未定义的错误

                mail=userData.mail 
                savedOrderData=location.state.savedOrder 
                onSubmit=onSubmit />

似乎我使用了来自 react-router-dom 的正确导入,但仍然无法解决问题。

【问题讨论】:

【参考方案1】:

为了将 history 等 props 传递给你的 route 组件,你必须使用 route 的 render props 来做到这一点。

在您的App.tsx 文件中进行必要的更改,如下所示。

<Route path="/order-form" render=props => (
                        <OrderForm ...props ...userData />
                    ) exact/>

并改变OrderForm组件函数参数如下得到location prop。

const OrderForm: React.FunctionComponent<UserData & RouteComponentProps<, StaticContext, LocationState>> = (userData: UserData, location: RouteComponentProps<, StaticContext, LocationState>) =>  

希望这能解决您的问题。

【讨论】:

我按照你说的做了,还是没有效果。你能解释一下const OrderForm: React.FunctionComponent&lt;UserData &amp; RouteComponentProps&lt;, StaticContext, LocationState&gt;&gt; = (userData: UserData, location: RouteComponentProps&lt;, StaticContext, LocationState&gt;) =&gt; 和你写的东西的区别吗?因为看起来一样 你保留它为 location ,但如果渲染道具通过location,那么你就得到了如上。你能输入...leftOver 来获取给组件的所有道具吗? (const OrderForm: React.FunctionComponent&lt;UserData &amp; RouteComponentProps&lt;, StaticContext, LocationState&gt;&gt; = (userData: UserData, ...leftOver: any) =&gt; ) 然后为leftOver 做一个控制台日志 由于某种原因,我仍然收到一个空对象。但我找到了使用 useLocation() 的解决方法。

以上是关于React BrowserRouter:位置未定义的主要内容,如果未能解决你的问题,请参考以下文章

React - useContext 返回未定义

React-Router:为啥react中未定义useHistory? [复制]

react-router-dom中的BrowserRouter和HashRouter

react-router-dom中的BrowserRouter和HashRouter

react-router-dom中的BrowserRouter和HashRouter

无法在 useParams 读取未定义的属性“匹配” - React Hooks