React + TS - 通过重定向传递参数

12 浏览
0 Comments

React + TS - 通过重定向传递参数

你好,我有一个应用程序,在成功创建新房间后想要将用户重定向到带有房间ID的页面。我想要在重定向时将数据发送到组件状态。

在App.tsx中,我有以下代码:

我在CreateRoom组件中这样进行重定向:

if(this.state.redirect) {
        return 
    }

这个重定向正常工作并将我重定向。以下是LobbyView的代码:

    import React, { Component } from 'react';
    import {BrowserRouter as Router, Route, Link, match} from 'react-router-dom';
    interface DetailParams {
        id: string;
    }
    interface Props {
        required: string;
        match?: match;
        ownerName?: string;
    }
    interface State {
        roomId?: string;
        ownerName?: string;
    }
    class LobbyView extends Component {
    constructor(props: Props) {
        super(props);
        this.state = {
            roomId: this.props.match?.params.id,
            ownerName: this.props.ownerName
        };
    }
    public render() {
        if(this.state.ownerName) {
            return (
                    

{this.props.match?.params.id}

You are owner of this room. ); }else { return (

{this.props.match?.params.id}

); } } } export default LobbyView;

但是,主要问题是,它将我重定向,但始终没有state参数ownerName。问题是:房间创建者将被重定向到URL以显示房间信息,并附带额外的所有者信息,如果他将此链接分享给其他用户,他们将没有所有者名称并且无法查看附加信息。

有人能帮帮我吗?我是React和TypeScript的新手,不知道该如何解决。非常感谢:)

0
0 Comments

React + TS - 重定向时如何传递参数

在React中,当我们使用重定向(redirect)功能时,有时需要将参数传递给目标页面。然而,在使用TypeScript时,我们可能会遇到一些问题,导致无法使用location属性。下面我们来看看问题的原因以及解决方法。

问题出现的原因是,当我们使用重定向时,目标页面的location属性可能无法直接访问。这是由于TypeScript的类型验证机制导致的。所以,我们需要对组件的props进行一些修改,以解决这个问题。

解决方法如下:

首先,我们需要导入react-router-dom库中的RouteComponentProps类型,以便修改组件的props类型定义。同时,我们还需要定义Params和LocationState两个接口,用于指定我们需要传递的参数类型。

接下来,在组件的props类型定义中,我们使用RouteComponentProps对props进行扩展。这样,我们就可以在组件中访问到location属性,并获取到传递的参数。

最后,我们需要注意的是,在重定向时,通常无需将数据从props或location state复制到组件的state中,除非有充分的理由需要这样做。

通过以上的修改,我们就可以在使用重定向功能时,成功传递参数给目标页面,并在目标页面中使用这些参数了。

以上就是关于React + TS中如何在重定向时传递参数的问题的原因和解决方法。希望对你有所帮助!

参考链接:

- [React Router - history](https://reactrouter.com/web/api/history)

- [React Router - Static Router](https://reactrouter.com/web/example/static-router)

0