Prz*_*mek 6 parameters url router reactjs react-hooks
<Photo>该应用程序在网格中显示所有照片<PhotoGrid>,然后单击后,函数会<Photo>使用 更改 URL history.push,并且 Router<Single>使用钩子根据 URL进行渲染useParams。
PhotoGrid-> Photo(单击时更改 URL)->Single基于 URL (useParams)。我一定搞砸了,因为 useParams 返回未定义。
感谢所有先进的想法。应用程序.js
class App extends Component {
render() {
return (
<>
<Switch>
<Route exact path="/" component={PhotoGrid}/>
<Route path="/view/:postId" component={Single}/>
</Switch>
</>
)
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
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>
)
}
Run Code Online (Sandbox Code Playgroud)
在照片中我用history.push更改URL
const selectPost = () => {
(...)
history.push(`/view/${post.code}`);
};
Run Code Online (Sandbox Code Playgroud)
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>
)
}
Run Code Online (Sandbox Code Playgroud)
Sza*_*yén 24
使用 useParams 时,您必须将解构let { postId } = useParams();与您的路径相匹配"/view/:postId"。
工作 Single.js
import { useParams } from "react-router-dom";
export default function Single() {
const { postId } = useParams();
console.log("this.context:", postId )
return (
<div className="single-photo">
{/* render something based on postId */}
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33824 次 |
| 最近记录: |