【发布时间】: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