我希望console.log('Refresh')
每次路由更改时都会运行(从Component1切换到Component2)。但这只是在第一次渲染时触发。为什么?
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;
答案 0 :(得分:4)
使用key属性,以便每次我们渲染新组件(不同的键)
<Route path='/mypath/:username' exact render= {routeProps =><MyCompo {...routeProps} key={document.location.href} />} />
答案 1 :(得分:4)
使用第二个参数useEffect有条件地应用效果。例如,通过react-router-dom,您可以获得一些属性
const { schoolId, classId } = props
useEffect(() => {
// fetch something here
}, [schoolId, classId)
此处[schoolId, classId
充当useEffect触发的唯一标识符。
答案 2 :(得分:3)
useEffect
不会被触发,因为App
组件没有被重新渲染,该组件没有任何变化(没有状态或道具更新)。
如果您希望在更改路线时重新渲染App
组件,则可以使用withRouter
HOC来注入路线道具,如下所示:
import { Switch, Route, withRouter } from 'react-router-dom';
const App = () => {
useEffect( () => console.log('Refresh'));
return (...);
}
export default withRouter(App);