[英]React Router v6 : How to render multiple component inside and outside a div with the same path
[英]React Router v6 render component on same page
我正在嘗試將一些“狀態可變”托管組件渲染更改為反應路由。我正在使用 react-router 6.3。 這是 App.js
function App() {
return (
<Router>
<Header />
<Selections />
<Routes>
<Route path='/:type' element={<PostMain />}>
<Route path=':comments' index element={<Comments />} />
</Route>
</Routes>
</Router>
);
}
這是組件
const handleLoadComments = () => {
if (!comments) {
dispatch(loadCommentsByPost(props.permalink));
} else {
navigate(-1);
//navigate(`/${type}`)
//console.log(type);
}
}
return (
<div className="Post">npm
<div className='Post-header' >
<p>Subbreddit: {props.subreddit_name_prefixed}</p>
<p>{created(props.created_utc)}</p>
</div>
<Media post={props} />
<div className='Post-footer-container' >
<div className='Post-footer' >
<div className='Post-footer-votes'>
<img src={upVote} alt="upvote" />
<p style={{color: "green"}} > {props.ups} -</p>
<img src={downVote} alt='downvote' />
<p style={{color: "red"}} > {props.downs}</p>
</div>
<Link to={`${props.id}`} >
<div className='Post-footer-comments' onClick={handleLoadComments} >
<input type="image" className='Comments-image' src={commentImg} alt='comment bubble' />
<p>{props.num_comments}</p>
</div>
</Link>
</div>
{/* { loading && <div className='Loading-container' ><img src={Loading} alt='loading' className='Comment-loading' /></div>} */}
</div>
<Outlet />
{/* {comments && <Comments comments={comments} />} */}
</div>
);
}
我的目標是在帖子下呈現評論,我之前用本地 state 和 setState 做到了,但是有沒有辦法用路由來做到這一點? 當我點擊評論時,我可以看到 url 的變化,我嘗試了“navigate( /${type}
)”,但甚至 url 也沒有改變,所以我使用了“navigate(-1)”,但是 Comments 組件沒有使成為! 提前致謝!
嘗試從評論路由中刪除路徑,因為它是默認情況下應該存在的索引
function App() {
return (
<Router>
<Header />
<Selections />
<Routes>
<Route path='/:type' element={<PostMain />}>
{/* <Route path=':comments' index element={<Comments />} /> */}
<Route index element={<Comments />} />
</Route>
</Routes>
</Router>
);
}
在您當前的方法中,您需要導航到/type/comments,但它應該只是/type
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.