Reactjs React routing-当我使用history.push传递URL时,URL中的id参数未定义
我设法在onClick中使用history.push,因为我想将用户id传递给配置文件页面组件,但URL中的uuid参数未定义,我不知道为什么。我真的被这部分难住了 我还想通过所有其他道具,我从随机用户生成器API,因为我在CardList中所做的事情,能够建立个人资料页面 非常感谢任何人的帮助Reactjs React routing-当我使用history.push传递URL时,URL中的id参数未定义,reactjs,react-redux,routes,react-router,react-router-dom,Reactjs,React Redux,Routes,React Router,React Router Dom,我设法在onClick中使用history.push,因为我想将用户id传递给配置文件页面组件,但URL中的uuid参数未定义,我不知道为什么。我真的被这部分难住了 我还想通过所有其他道具,我从随机用户生成器API,因为我在CardList中所做的事情,能够建立个人资料页面 非常感谢任何人的帮助 import React, { Fragment } from "react"; import { withRouter } from "react-router-dom"; const Card =
import React, { Fragment } from "react";
import { withRouter } from "react-router-dom";
const Card = ({ history, firstName, lastName, email, uuid, image, city, country }) => {
return (
<Fragment>
<div className="tc bg-washed-green dib br3 pa3 ma2 dim bw2 shadow-5 pointer">
<img src={image} alt="userImage" onClick={() => history.push(`/profilepage/${uuid}`)} />
<h2>{`${firstName} ${lastName}`}</h2>
<p> {email} </p>
<div>
<span>{`${city}, ${country}`}</span>
</div>
</div>
</Fragment>
);
};
export default withRouter(Card);
这是App.js中的路由
render() {
const { users, isPending } = this.props;
if (isPending) {
return <h1 className="tc"> Loading... </h1>;
} else {
return (
<div className="tc">
<Switch>
<Route exact path="/homepage" render={() => <CardList users={users} />} />
<Route path="/profilepage/:uuid" component={ProfilePage} />
</Switch>
</div>
);
}
}
}
编辑:看起来你没有将uuid作为道具发送。你能检查一下卡片列表组件吗
这是未定义的,因为它实际上不是作为道具发送uuid数据。您应该从this.props.match.params.uuid获取它
您还可以检查url中是否存在您的id吗?如果是这样,我的方法应该有效
从react router dom version 5中,您可以使用类似于钩子的useParams。因此,您可以在ProfilePage组件中使代码库更加清晰,您可以通过以下方式获得uuid
方法1:在这种方法中,您要么需要传播所有其他将从父级发送的道具,要么需要使用…rest参数来捕获所有其他您不想传播的道具。
从React导入React,{Fragment};
const ProfilePage={match}=>{
回来
配置文件页:{match.params.uuid}
;
};
导出默认配置文件页面;
方法2:这样你也可以使用其他道具
从React导入React,{Fragment};
const ProfilePage=props=>{
回来
配置文件页面:{props.match.params.uuid}
;
};
导出默认配置文件页面;
我的id在url中显示为未定义的“是”。我不太明白如何使用这个.props.match.params.uuid获取它。你能详细说明一下吗?
render() {
const { users, isPending } = this.props;
if (isPending) {
return <h1 className="tc"> Loading... </h1>;
} else {
return (
<div className="tc">
<Switch>
<Route exact path="/homepage" render={() => <CardList users={users} />} />
<Route path="/profilepage/:uuid" component={ProfilePage} />
</Switch>
</div>
);
}
}
}
import React, { Fragment } from "react";
import Card from "./Card";
const CardList = ({ users }) => {
return (
<Fragment>
<h1 className="f1"> IOTA Users </h1>
{users.map((user) => {
return (
<Card
key={user.login.uuid}
image={user.picture.large}
firstName={user.name.first}
lastName={user.name.last}
email={user.email}
city={user.location.city}
country={user.location.country}
/>
);
})}
</Fragment>
);
};
export default CardList;