javascript - 使用 useParams 从 url 获取值
问题描述
我有一个带有 Material-UI 的 React 表单。我想使用从 URL 链接获取 iduseParams
并发出一些 API 请求以填充表单数据:
http://localhost:3001/profile?ids=9459377
主app.tsx:
function App() {
return (
<Router>
<Navbar />
<Switch>
<Route path='/ticket-profile/:ids' component={TicketProfile} />
</Switch>
</Router>
);
}
我使用此代码打开一个新页面并传递ids
参数:
history.push(`/ticket-profile/ids=${id}`)
我需要将数据放入此页面:
export default function TicketProfile(props: any) {
let { ids } = useParams();
const [ticket, setTicket] = useState<TicketDTO[]>([]);
useEffect(() => {
getSingleTicket();
}, []);
const getSingleTicket = async () => {
getTicket(ids)
.then((resp) => {
setTicket(resp.data);
})
.catch((error) => {
console.error(error);
});
}
但是对于这条线let { ids }
,我得到:
TS2339: Property 'ids' does not exist on type '{}'.
你知道我该如何解决这个问题吗?
解决方案
所以这是网址
http://localhost:3001/profile?ids=9459377
在您的代码中
const MyComponent = () => {
const params = new URLSearchParams(window.location.search);
就是这样!现在我们应该继续获取值并检查查询字符串的存在
检查是否有查询;
params.has('ids')
或获取查询字符串中的值
params.get('ids')
您也可以有条件地显示它们
console.log(params.has('ids')?params.get('ids'):"")
更新:
查看工作示例https://codesandbox.io/s/peaceful-https-vz9y3?file=/src/App.js\ 这就是我们在你的情况下应该如何使用它
export default function TicketProfile(props: any) {
const params = new URLSearchParams(window.location.search);
const ids = params.get('ids');
const [ticket, setTicket] = useState<TicketDTO[]>([]);
useEffect(() => {
getSingleTicket();
}, []);
const getSingleTicket = async () => {
getTicket(ids)
.then((resp) => {
setTicket(resp.data);
})
.catch((error) => {
console.error(error);
});
}
推荐阅读
- c++ - typedef decltype 函数指针未返回正确的输出 (cout)
- python - Django中的日期字段验证
- html - 如何从 Google 电子表格中的 html 元素获取内容?
- c++ - 解析 PLT 存根地址和名称
- python - 在 Python 中使用带有日期的迭代行
- node.js - Who is productive Model.prototype.save() or Model.create()?
- javascript - PWA 添加到主屏幕弹出按钮不起作用
- node.js - 如何修复:在 Jest 中运行测试时“TypeError:wsModule.Server 不是构造函数”
- docker - 公开你的应用程序在本地 kubernetes 集群上不起作用
- python - 您如何根据与列表中每个项目的条件匹配来过滤索引?