Javascript 反应+;TS-使用重定向传递参数
您好,我有一个应用程序,我想在成功创建新房间后重定向用户。 我想将他重定向到URL中带有房间ID的页面,但我想用这个重定向将数据发送到组件状态 在App.tsx中,我有Javascript 反应+;TS-使用重定向传递参数,javascript,reactjs,typescript,react-router,Javascript,Reactjs,Typescript,React Router,您好,我有一个应用程序,我想在成功创建新房间后重定向用户。 我想将他重定向到URL中带有房间ID的页面,但我想用这个重定向将数据发送到组件状态 在App.tsx中,我有 <Route path="/game/lobby/:id" component={LobbyView} /> 像这样从CreateRoom组件进行im重定向 if(this.state.redirect) { return <Redirect to={{
<Route path="/game/lobby/:id" component={LobbyView} />
像这样从CreateRoom组件进行im重定向
if(this.state.redirect) {
return <Redirect to={{
pathname: "/game/lobby/" + this.state.roomId,
state: { ownerName: this.state.roomOwnerName }
}}/>
}
if(this.state.redirect){
返回
}
这很好,可以让我改变方向。
这是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;
import React,{Component}来自'React';
从“react Router dom”导入{BrowserRouter as Router,Route,Link,match};
接口详细信息参数{
id:字符串;
}
界面道具{
必需:字符串;
匹配?:匹配;
所有者名称:字符串;
}
界面状态{
roomId?:字符串;
所有者名称:字符串;
}
类LobbyView扩展组件{
建造师(道具:道具){
超级(道具);
此.state={
室友:这个。道具。匹配?。参数id,
ownerName:this.props.ownerName
};
}
公共渲染(){
if(this.state.ownerName){
返回(
{this.props.match?.params.id}
您是这个房间的主人。
);
}否则{
返回(
{this.props.match?.params.id}
);
}
}
}
导出默认的LobbyView;
但有一个主要问题,它重定向我,但总是没有状态参数ownerName
要点是:文件室的创建者将被重定向到URL,以显示文件室信息和所有者的其他信息,如果他将此链接共享给其他用户,则他们的ownerName将为空,并且他们无法查看其他信息
有人能帮我吗?我对react和typescript是新手,我不知道怎么做。。
非常感谢:)位置状态数据将在
位置中提供。状态
this.props.location.state?.ownerName
//或
这个。道具。历史。地点。州?。所有者姓名
因此,您可以:
if(this.props.location.state?.ownerName) {
..
}
看到这个物体了吗
而且,除非您有充分的理由这样做,否则无需将数据从“道具”或“位置状态”(您的案例)复制到“组件状态”
下面是如何修复组件道具的键入问题(将其与react router dom提供的RouteProps结合起来):
从“react router dom”导入{RouteComponentProps};
接口参数{
id:字符串;
}
接口位置状态{
所有者名称:字符串;
}
//使用静态路由器时,静态上下文可用*
接口SC{
状态码?:编号;
}
类LobbyView扩展组件
*这种情况很可能发生,因为您正试图从道具中获取您的状态-过去有一个React组件生命周期componentWillReceiveProps
不确定它是否仍然可用。我建议阅读这里的答案:嗯,我不能使用位置,因为这是未定义的属性。可能是类型脚本验证。这就是问题所在。是的,它起作用了。非常感谢:))
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>