本文介绍了useParams 钩子在反应功能组件中返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用在网格中显示所有照片,然后一旦点击,中的一个功能code> 使用 history.push 更改 URL,Router 使用 useParams 钩子根据 URL 呈现 .

PhotoGrid ->Photo(在点击时更改 URL)->Single 基于 URL (useParams).我一定是搞砸了什么,因为 useParams 返回 undefined.

感谢所有先进的想法.应用程序

class App 扩展组件 {使成为() {返回 (<><开关><路由精确路径="/";组件={PhotoGrid}/><路由路径="/view/:postId";组件={单}/></开关></>)}}导出默认应用程序;

Photogrid.js

导出默认函数 PhotoGrid() {const 帖子 = useSelector(selectPosts);返回 (<div>你好{/* {console.log(posts)} */}{posts.map((post, i) => <Photo key={i} i={i} post={post}/>)}

)}

在照片中我使用 history.push 更改 URL

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

Single.js

import { useParams } from react-router-dom";导出默认函数 Single() {让 { id } = useParams();console.log("id:", id)//返回未定义返回 (<div className=单张照片">id 是:{id}//不渲染任何东西

)}

解决方案

当使用 useParams 时,你必须将解构 let { postId } = useParams(); 匹配到你的路径 "/view/:postId".

工作 Single.js

import { useParams } from react-router-dom";导出默认函数 Single() {让 { postId } = useParams();console.log("this.context:", postId )返回 (<div className=单张照片">{/* 根据 postId 渲染一些东西 */}

)}

The app displays all photos <Photo> in a grid <PhotoGrid>, then once clicked, a function in <Photo> changes URL with history.push, and Router renders <Single> based on URL using useParams hook.

PhotoGrid -> Photo (changes URL onClick) -> Single based on URL (useParams).I must have messed something up, becouse useParams returns undefined.

Thanks for all ideas in advanced.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>
    )
}

in Photo I change URL with 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>
    )
}
解决方案

When using useParams, you have to match the destructure let { postId } = useParams(); to your path "/view/:postId".

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

这篇关于useParams 钩子在反应功能组件中返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 13:43