您好,我有一个应用程序,我想在成功创建新房间后重定向用户。 我想将他重定向到 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 和 typescript 的新手,我不知道该怎么做。 非常感谢你:)
最佳答案
位置状态数据将在 location.state
中提供:
this.props.location.state?.ownerName
// OR
this.props.history.location.state?.ownerName
所以,你可以这样做:
if(this.props.location.state?.ownerName) {
..
}
查看此history对象。
并且不需要将数据从“props”或“位置状态”(您的情况)复制到“组件状态”,除非您有充分的理由这样做。
以下是如何修复组件属性的类型(将其与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>
关于javascript - React + TS - 通过重定向传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66724914/