【问题标题】:Accessing router properties outside Switch component在 Switch 组件之外访问路由器属性
【发布时间】:2017-07-07 12:17:58
【问题描述】:

我正在使用 react-dom-router(React 路由器 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 只是从一个对象映射路线

我想在页眉中显示页面的标题,但是,如果我单击侧边栏中的任何链接,它不会更新 Header 类中的 this.props.match 对象。 (它总是有一个path '/')

是否可以在 react-router 更改路由时更新 Header props?

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    因此,解决此问题的一种方法是聆听历史。 我最终将标题标题用于单独的组件:

    // @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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-23
      • 2016-04-14
      • 2019-05-04
      • 2010-10-20
      • 2017-02-18
      • 2014-05-29
      • 1970-01-01
      • 2018-08-01
      相关资源
      最近更新 更多