简体   繁体   English

反应路由器不重新渲染相同<Link>道具上的组件

[英]React Router not rerendering same <Link> component on props

Problem问题
I have two same React Router pointing to same component but there are two different props being passed.我有两个相同的 React Router 指向同一个组件,但是传递了两个不同的道具。 React Router doesn't seem to rerender the component thus the changes are not being shown React Router 似乎没有重新渲染组件,因此没有显示更改

App.js应用程序.js

function App() {
  return (
    <Router>
      <div className="App">
        <Switch>
          <Route path="/" exact component={Main}/>
          <Route path="/FAQ" component={Faq}/>
        </Switch>
      </div>
    </Router>
    
  );
}

Header标题

<Link to="/" ><li className="active">HOME</li></Link>
<Link to={{ pathname: '/FAQ', state: { Display: "about"} }} ><li>ABOUT</li></Link>
<Link to={{ pathname: '/FAQ', state: { Display: ""} }} ><li>FAQ</li></Link>

Faq.js常见问题解答

<Accordion className="accordion" preExpanded={[props.location.state.Display]} >

The site works as expected if for example i go Home > About, or Home > FAQ, but in case i go FAQ > About or About > FAQ, the site doesn't rerender and the "accordion" doesn't pre expend even tho props get changed on FAQ.js because i console logged them.该网站按预期工作,例如,如果我转到“主页”>“关于”或“主页”>“常见问题”,但如果我转到“常见问题”>“关于”或“关于”>“常见问题”,则该网站不会重新呈现,并且“手风琴”也不会预先消耗道具在 FAQ.js 上被更改,因为我控制台记录了它们。

Base on your code, the component will not re-render since you are not change the state which its trigger any re-render event for react life-cycle...根据您的代码,该组件不会重新渲染,因为您不会更改其触发任何重新渲染事件以进行反应生命周期的状态...

So, I prefer to change your code from location state to URL param, since base on your logic here, this what you needed, for example:因此,我更喜欢将您的代码从位置状态更改为 URL 参数,因为根据您在此处的逻辑,这是您需要的,例如:

    <Switch>
      <Route path="/" exact component={Main}/>
      <Route path="/FAQ/:slug?" component={Faq}/>
    </Switch>

and in your Faq Component:并在您的常见问题组件中:

let { slug } = useParams();

now, when you click on Link:现在,当您单击链接时:

About or Faq 关于或常见问题

re-render will trigger, since theirs a state is changed...重新渲染将触发,因为他们的状态已更改...

Note: :slug?注意: :slug? we add a question mark here to make it optional...so you can send about or not.我们在此处添加一个问号以使其可选...因此您可以发送或不发送。

Note 2: if you need to re-render base on state, simply you can add hook and lesion to location.state and trigger update manually on useState or by any action you like...like add a key props thats contain location.state.myKey value注意 2:如果您需要根据状态重新渲染,只需将钩子和病变添加到 location.state 并在 useState 上手动触发更新或通过您喜欢的任何操作...例如添加包含 location.state 的关键道具.myKey 值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM