我正在React中构建一个应用程序,并试图让导航栏在用户导航到其他页面时进行更新。但是,检测位置道具的变化并不一致。
如果我转到主页并刷新页面,然后单击“帐户”链接,则“帐户”和Navbar location.pathname属性均按预期方式从“ /”更改为“ Account”,并且控制台正确写入“ change” “。
如果我再单击“主页”链接,则导航栏会再次正确检测到路线更改。
但是,如果我现在再次单击“帐户”,则导航栏的位置不会更新,它保持为“ /”并且未检测到更改。
我看不到这两种情况之间有什么区别,但是第一次单击“帐户”而不是第二次时,它始终有效。
我已经阅读了有关blocking components的React Router文档,但我认为这不是问题所在,因为导航栏是顶级组件,我使用“位置”作为道具,不使用purecomponent,并且Account组件会更新。而且我认为,如果这是问题所在,那将永远无法解决?
有人可以建议我如何让导航栏一致地检测路线何时发生变化吗?谢谢!
Navbar.js:
class Navbar extends Component {
constructor(props) {
super(props);
}
componentDidUpdate = (prevProps) => {
console.log('***');
console.log('nav old pathname', prevProps.location.pathname);
console.log('nav new pathname', this.props.location.pathname);
if (prevProps.location.pathname !== this.props.location.pathname) {
// this usually doesn't trigger on navigate
console.log('change');
}
}
render() {
...render my html
}
}
export default connect(mapStateToProps)(withRouter(Navbar));
App.js:
const App = () => (
<Provider store={store}>
<Router>
<div>
<Navbar />
<div className="container">
<Route exact path="/" component={Home} />
<Route exact path="/account" component={Account} />
</div>
</div>
</Router>
</Provider>
);
export default App;
来自package.json:
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.18",
"@fortawesome/free-regular-svg-icons": "^5.8.2",
"@fortawesome/free-solid-svg-icons": "^5.8.2",
"@fortawesome/react-fontawesome": "^0.1.4",
"bootstrap": "^4.2.1",
"classnames": "^2.2.6",
"formik": "^1.5.7",
"i": "^0.3.6",
"jquery": "^3.4.0",
"jwt-decode": "^2.2.0",
"normalizr": "^3.3.0",
"npm": "^6.9.0",
"prop-types": "^15.7.2",
"react": "^16.8.2",
"react-dom": "^16.8.2",
"react-markdown": "^4.0.6",
"react-redux": "^6.0.0",
"react-router-dom": "^4.3.1",
"react-scripts": "3.0.0",
"react-widgets": "^4.4.11",
"reactstrap": "^7.1.0",
"redux": "^4.0.1",
"redux-devtools-extension": "^2.13.8",
"redux-thunk": "^2.3.0",
"reselect": "^4.0.0",
"updeep": "^1.1.0"
},
答案 0 :(得分:1)
将 Switch 从react-router-dom导入到您的 App.js
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
const App = () => (
<Provider store={store}>
<Router>
<div>
<Navbar />
<div className="container">
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/account" component={Account} />
</Switch>
</div>
</div>
</Router>
</Provider>
);
export default App;
不要忘记导入导航栏,主页和帐户
答案 1 :(得分:0)
问题出在这一行:
export default connect(mapStateToProps)(withRouter(Navbar));
您未使用PureComponent
,但正在使用connect
。您可以通过以下方式解决此问题:
1。反转组成:
export default withRouter(connect(mapStateToProps)(Navbar));
2。在mapStateToProps
中向下传递位置道具:
const mapStateToProps(state, ownProps) {
return {
location: ownProps.location
}
}