解决/A/:id 跳转到另一个/A/:id

ant design 的跳转,一般我们不需要用到window.location.href跳转,毕竟是直接页面刷新,比如

window.location.href = `/literatureInfo/${xiaData}`

我们一般不会去使用这个,因为是直接页面刷新,而我们可能只需要刷新数据即可。

而我们更多是用到

使用 useNavigate 来手动触发跳转

{/* 上方的按钮行 */}
<Row justify="space-between" style={{ marginBottom: '10px' }}>
    <Col>
        <Button type="primary" onClick={goToPreviousChapter}>
            上一章
        </Button>
    </Col>
    <Col>
        <Button type="primary" onClick={goToNextChapter}>
            下一章
        </Button>
    </Col>
</Row>
npm install react-router-dom

import { useNavigate } from 'react-router-dom'; 
const navigate = useNavigate();

const goToPreviousChapter  = () => {
  navigate(`/literatureInfo/${lData?.pre}`);
};

const goToNextChapter = () => {
  navigate(`/literatureInfo/${lData?.after}`);
};

 

或者直接link跳转

<Row justify="space-between" style={{ marginBottom: '10px' }}>
  <Col>
    <Button
      type="primary"
    >
      <Link to={'/literatureInfo/' + lData?.pre}>
        上一章
      </Link>
    </Button>
  </Col>
  <Col>
    <Button
      type="primary"
    >
      <Link to={'/literatureInfo/' + lData?.after}>
        下一章
      </Link>
    </Button>
  </Col>
</Row>

 

注意这两种方法一般情况应该是可以的。

比如用于/literatureInfo/:id 跳转到/literatureBankList/:id 就可以,这已经不是同一个组件实例所以正常跳转。

但是如果出现

从 /literatureInfo/:id 跳转到另一个 /literatureInfo/:id 时页面内容就会出现不更新。

表现的情况就是

明明已经点击跳转了,浏览器上面也出现了新的/literatureInfo/:id ,为什么数据不刷新呢?

这是因为 React Router 默认会复用同一个组件实例。

解决方法很简单。

只要useEffect监听params.id也就是/literatureInfo/:id的:id就可以触发刷新。

useEffect(() => {
    //加载页面函数
    loadData();
}, [params.id]);
const loadData = async () => {
    if (!params.id) {
        ......
    }
    ......
    const res = await getLiteratureVoByIdUsingGet({
        id: params.id,
    });
    setLData(res.data);
    ......
};

 

 

暂无评论

发送评论 编辑评论

|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇