【问题标题】:React + TS - pass parameters with redirectReact + TS - 使用重定向传递参数
【发布时间】:2021-06-17 20:24:29
【问题描述】:

您好,我有一个应用程序,我想在成功创建新房间后重定向用户。 我想将他重定向到 URL 中带有房间 ID 的页面,但我想通过此重定向将数据发送到组件状态。

在 App.tsx 我有

<Route path="/game/lobby/:id" component={LobbyView} />

我像这样从 CreateRoom 组件重定向

if(this.state.redirect) {
        return <Redirect to={{
            pathname: "/game/lobby/" + this.state.roomId,
            state: { ownerName: this.state.roomOwnerName }
        }}/>
    }

效果很好并重定向我。 这是 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<DetailParams>;
        ownerName?: string;
    }

    interface State {
        roomId?: string;
        ownerName?: string;
    }

    class LobbyView extends Component<Props, State> {

    constructor(props: Props) {
        super(props);

        this.state = {
            roomId: this.props.match?.params.id,
            ownerName: this.props.ownerName
        };
    }

    public render() {
        if(this.state.ownerName) {
            return (
                <div>
                    <h1>{this.props.match?.params.id}</h1>
                    <strong>You are owner of this room.</strong>
                </div>
            );
        }else {
            return (
                <h1>{this.props.match?.params.id}</h1>
            );
        }
    }
   }
   export default LobbyView;

但有一个主要问题,它重定向了我,但总是没有状态参数 ownerName..

关键是:房间的创建者将被重定向到 URL 以显示房间信息以及所有者的附加信息,如果他将此链接分享给其他用户,他们的 ownerName 将为空,他们无法查看附加信息。

有人可以帮帮我吗?我是反应和打字稿的新手,我不知道该怎么做.. 非常感谢:)

【问题讨论】:

  • 这很可能是因为你试图从道具中获取你的状态 - 曾经有一个 React 组件生命周期componentWillReceiveProps 不确定它是否仍然可用。我建议在这里阅读答案:stackoverflow.com/questions/40063468/…

标签: javascript reactjs typescript react-router


【解决方案1】:

位置状态数据将在 location.state 中提供:

this.props.location.state?.ownerName
// OR
this.props.history.location.state?.ownerName

所以,你可以这样做:

if(this.props.location.state?.ownerName) {
  ..
}

查看此history 对象。

除非您有充分的理由,否则无需将数据从“props”或“location state”(您的情况)复制到“component state”。

这里是如何fix Typings组件道具(将它与 react-router-dom 提供的 RouteProps 结合使用):

import { RouteComponentProps } from "react-router-dom";

interface Params {
  id: string;
}

interface LocationState {
  ownerName: string;
}

// Static Context is available when you use Static Router*
interface SC {
  statusCode?: number;
}

class LobbyView extends Component<Props & RouteComponentProps<Params, SC, LocationState>, State>

*Static Router

【讨论】:

  • 嗯,我不能使用位置,因为这是未定义的属性。可能是 Typescript 验证。这就是问题所在..
猜你喜欢
  • 2020-05-03
  • 1970-01-01
  • 2020-06-11
  • 2013-06-08
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
相关资源
最近更新 更多