【问题标题】:When I react-router to change the page, the rendering isn't work with React当我 react-router 更改页面时,渲染不适用于 React
【发布时间】:2021-02-17 10:01:29
【问题描述】:

我想用我创建的 news.json 文件创建新的列表页面。

如下所示,在我用 ${item.id} 制作链接 href 的同时,用地图制作列表

item.is 代表 news1、news2、new3.. 等,我让每一个 new1.js、new2.js 与它链接。

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

我已经用谷歌搜索过了,发现 * 发帖,说路由器需要密钥.. 类似的东西,但我还是不明白。

我如何更改我的代码???

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;

【问题讨论】:

    标签: javascript json react-router rendering link-to


    【解决方案1】:

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

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

    【讨论】: