首页 > 解决方案 > 使用 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 '{}'.

你知道我该如何解决这个问题吗?

标签: javascriptreactjstypescript

解决方案


所以这是网址

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);
            });
    }

推荐阅读