当我反应路由器更改页面时,渲染不适用于 React



我想让新的列表页面与新闻。

如下所示,在我使用${item.id}创建Link href的同时,使用map创建列表

项目。代表news1, news2, new3…等等,我让每个new1.js, new2.js与它链接。

但是当我这样做的时候,它没有显示任何身体。我认为渲染有问题。

我已经谷歌它,发现stackoverflow张贴,它说路由器需要密钥。差不多吧,但我还是不明白。

我如何改变我的代码?

const NewWrap =()=>{
const articleWrapper = news.map((item)=>{
return(
<Li key ={item.id}>

<img src={item.img} alt="img"  style ={{width:"260px", height:"200px", padding:"1rem"}}/>
**<Link to={`/${item.id}`}** style={{textDecoration:"none", color:"black"}}>
<div style={{padding:"1rem", textAlign:"left", cursor:"pointer"}}>
<p>{item.title}</p>
<p>{item.content.substring(0,305)}...</p>
<p >{item.date}</p>
</div>
</Link>
</Li>

)
});
return(
<Ul>
{articleWrapper}
</Ul>
)
}
const News = () => {

return (
<div>

<ImgBox>
<Img src ="../img/bg_mian_01.png"/>
<ImgText>News and Partners</ImgText>
</ImgBox>

<ConBox>
<Subtitle>NEWS</Subtitle> 
<NewWrap/>
</ConBox>
<Switch>
<Route path="/new1" component={New1}/>
</Switch>
</div>

);
};
export default News;

在最新版本的React Router (v6)中,你不再使用Switch,你必须指定一个元素而不是一个组件。

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
<Router>
<Routes>
<Route path="/new1" element={<New1 />} />
</Routes>
</Router>