【发布时间】:2021-11-07 14:20:04
【问题描述】:
这里是超级菜鸟...
所以,我有这个学校项目,但事情变得有点困难......
我正在尝试将一些道具从一个组件传递到另一个组件,但我不知道为什么它总是失败。
因此,这个想法是,当有人从一个组件中选择一个选项时,用户将被重定向到具有该选择的 ID 或编号的另一个页面,因此某些内容将从数据库中提取并呈现在屏幕上.
重定向部分似乎是简单的部分。这是代码:
{this.state.selectedCityCode > 0 && (
<Redirect
to={{
pathname: `/deals/${this.state.selectedCityCode}/${this.state.selectedCityName}`,
state: {
cityCode: this.state.selectedCityCode,
cityName: this.state.selectedCityName
}
}}
/>
)}
现在,重定向按预期工作,url 发生变化,新组件 ger 呈现错误,因为 ID 没有传递,或者目标组件没有得到它。
在路由器组件中,这是重定向的相关部分:
<Route exact path="/deals/:cityCode/:cityName" component={AllDeals}></Route>
在目标组件中,这是相关部分——据我所知——
interface AllDealsProps {
cityCode: number;
cityName: string;
}
还有这个:
public componentDidMount = async () => {
const response = await axios.get<Deal[]>( http://localhost/destinations/${this.props.cityCode}/all );
this.setState({ deals: response.data }); };
我用过:
import { useParams } from "react-router-dom";
并尝试这样做:
public componentDidMount = async () => {
const params = useParams();
const response = await axios.get<Deal[]>(
`http://localhost:4000/destinations/${this.props.cityCode}/deals`
);
this.setState({ deals: response.data });
};
问题是,“cityCode”和“cityName”永远不会被拾取并且永远是未定义的。
我看到了一些关于使用的东西:
this.props.location.state.cityCode
但它总是会说“'Readonly & Readonly'.ts(2339) 类型上不存在属性 'location'”
【问题讨论】:
标签: typescript react-typescript react-tsx