useParams hook returns 在反应功能组件中未定义

useParams hook returns undefined in react functional component

该应用程序在网格 <PhotoGrid> 中显示所有照片 <Photo>,然后单击后,<Photo> 中的函数将 URL 更改为 history.push,并且路由器使用 useParams 钩子基于 URL 呈现 <Single>

PhotoGrid -> Photo(更改 URL onClick) -> Single 基于 URL(useParams)。 我一定是搞砸了,因为 useParams returns undefined.

感谢所有先进的想法。 App.js

class App extends Component {
  render() {
    return (
      <>
        <Switch>
          <Route exact path="/" component={PhotoGrid}/>
          <Route path="/view/:postId" component={Single}/>
        </Switch>
      </>
    )
  }
}
export default App;

Photogrid.js

export default function PhotoGrid() {
    const posts = useSelector(selectPosts);

    return (
        <div>
            hi
            {/* {console.log(posts)} */}
            {posts.map((post, i) => <Photo key={i} i={i} post={post} />)}
        </div>
    )
}

在照片中,我将 URL 更改为 history.push

const selectPost = () => {
  (...)
  history.push(`/view/${post.code}`);
  };

Single.js

import { useParams } from "react-router-dom";
export default function Single() {
    let { id } = useParams();
    console.log("id:",  id)   //returns undefined

    return (
      <div className="single-photo">
       the id is: {id} //renders nothing
      </div>
    )
}

使用 useParams 时,您必须将解构 let { postId } = useParams(); 与您的路径 "/view/:postId".

相匹配

工作Single.js

import { useParams } from "react-router-dom";

export default function Single() {
    let { postId } = useParams();
    console.log("this.context:",  postId )

    return (
      <div className="single-photo">
        {/* render something based on postId */}
      </div>
    )
}

您应该使用与路由路径中提到的相同的解构。在这种情况下,您应该写成:

let { postID } = useParams();

我会再提两个有人可能犯的错误并面临同样的问题:

  1. 您可以使用 Router 组件代替 Route 组件。
  2. 您可能会忘记在 Route 组件的路径属性中提及该参数,而您会在 Link 组件中提及它。