我正在使用react-dom-router(React router v.4)
应用布局:
<div className={classes.root}>
<Header />
<div className={classes.body} >
<Sidebar />
<div className={classes.content} >
<Switch>
{mapRoutes(routes)}
</Switch>
</div>
</div>
</div>
index.js:
ReactDom.render(
<Provider store={store}>
<Router>
<MuiThemeProvider theme={theme}>
<App />
</MuiThemeProvider>
</Router>
</Provider>
, MOUNT_NODE);
mapRoutes
只是映射来自对象的路径
我想在标题中包含页面,但是,如果我单击侧边栏中的任何链接,它将不会更新this.props.match
类中的Header
对象。 (它总是有path
的'/')
当react-router更改路由时,是否可以更新Header props?
答案 0 :(得分:0)
因此解决这个问题的一种方法是听取历史。 我最终把标题标题分成了单独的组件:
// @flow
import React from 'react';
import PropTypes from 'prop-types';
import routeToLabel from 'helpers/routeToLabel';
import { withRouter } from 'react-router-dom';
// $FlowIgnore flow bug
import Typography from 'material-ui/Typography';
class HeaderTitle extends React.Component {
static propTypes = {
className: PropTypes.string.isRequired,
location: PropTypes.shape({
pathname: PropTypes.string,
}).isRequired,
history: PropTypes.shape({
push: PropTypes.func,
listen: PropTypes.func,
}).isRequired,
}
constructor(props) {
super(props);
this.state = {
pathname: props.location.pathname,
};
}
state = {}
componentDidMount() {
this.unlisten = this.props.history.listen(this.updateHeaderTitle);
}
componentWillUnmount() {
this.unlisten();
}
// Need this placeHolder else an error is thrown
unlisten = () => {}
updateHeaderTitle = (location) => {
if (location.pathname !== this.state.pathname) {
this.setState({ pathname: location.pathname });
}
}
render() {
const { className } = this.props;
const { pathname } = this.state;
return (
<Typography type="title" color="inherit" className={className}>
{routeToLabel(pathname)}
</Typography>
);
}
}
const routedClass = withRouter(HeaderTitle);
export default routedClass;