Reaction Use Effect在路线更改时不触发

React useEffect is not triggering on route change(Reaction Use Effect在路线更改时不触发)

本文介绍了Reaction Use Effect在路线更改时不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期望console.log('Refresh')在每次路由更改(从组件1切换到组件2)时运行。但它只在第一次渲染时触发。为什么?

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));

App.js

import React, { useEffect } from 'react';
import { Switch, Route } from 'react-router-dom';
import Nav from './Nav';
import Component1 from './Component1';
import Component2 from './Component2';

const App = () => {

  useEffect( () => console.log('Refresh'));

  return (
        [<Switch>
            <Route                            component = {Nav}/>
        </Switch>,
        <Switch>
            <Route exact path = '/component1' component = {Component1}/>
            <Route exact path = '/component2' component = {Component2}/>
        </Switch>]
  );
}

export default App;

Nav.js

import React from 'react';
import { Link } from 'react-router-dom';

const  Nav = () => {
  return (
    <div>
        <Link to = '/component1'>Component 1</Link>
        <Link to = '/component2'>Component 2</Link>
    </div>
  );
}

export default Nav;

Component1.js

import React from 'react';

const  Component1 = () => {

  return (
    <div>
        <p>Hi</p>
    </div>
  );
}

export default Component1;

Component2.js

import React from 'react';

const  Component2 = () => {
  return (
    <div>
        <p>Bye</p>
    </div>
  );
}

export default Component2;

推荐答案

未触发useEffect,因为App组件未重新呈现,该组件中没有任何更改(没有状态或道具更新)。

如果希望在路线更改时重新呈现App组件,可以使用withRouter点注入路线道具,如下所示:

import { Switch, Route, withRouter } from 'react-router-dom';

const App = () => {

  useEffect( () => console.log('Refresh'));

  return (...);
}

export default withRouter(App);

示例:https://codesandbox.io/s/youthful-pare-n8p1y

这篇关于Reaction Use Effect在路线更改时不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Reaction Use Effect在路线更改时不触发