无法在React Router V4中将状态设置为location.pathname

时间:2017-11-16 13:38:00

标签: reactjs react-router-v4

我尝试将组件的状态设置为URL的当前路径名。具体来说,我想在App.js中定义的ResponsiveDrawer组件中执行此操作:

class App extends Component {
  render() {
    return (
      <Router>
        <ResponsiveDrawer>
          <div className="App">
            <Route exact path="/" component={Administrator} />
            <Route path="/admin" component={Administrator} />
            <Route exact path="/jobs" component={Jobs} />
            <Route path="/jobs/:id" render={({match}) => <ViewJob id={match.params.id} />} />
            <Route path="/entries/:jobId/:entryId" render={({match}) => <Entry jobId={match.params.jobId} entryId={match.params.entryId} />} />
            <Route exact path="/reports" component={Reports} />
            <Route path="/reports/:jobId" render={({match}) => <JobReport id={match.params.jobId} />} />
            <Route path="/reports/activity" component={ActivityReport} />
          </div>
         </ResponsiveDrawer>
     </Router>

    );
  }
}

现在,在ResponsiveDrawer组件中,我有以下代码,以便在URL更改时触发:

class ResponsiveDrawer extends React.Component {
  constructor() {
    super();
    this.state = {
      mobileOpen: false,
      adminOpen: true,
      jobsOpen: false,
      reportsOpen: false,
      activePath: ''
    };
    this.setActiveState = this.setActiveState.bind(this);
    this.isActiveFunc = this.isActiveFunc.bind(this);
  }


  setActiveState = (path) => {
    this.setState({activePath: path});
  };

  isActiveFunc = (match, location) => {
    console.log(location.pathname)
    this.setActiveState(location.pathname);
    return match
  };

  render() {  
      <NavLink isActive={this.isActiveFunc} className={classes.subLink} to={{ pathname: "/admin/users" }}>
         <ListItem button className={classes.nested}>
         <ListItemText inset primary="Users" />
         </ListItem>
       </NavLink>

每次单击NavLink时,都会正确记录当前位置。但是,当我尝试将状态设置为location.pathname的值时,我收到以下错误:

  

proxyConsole.js:54警告:在现有状态期间无法更新   过渡(例如在render或其他组件内   构造函数)。渲染方法应该是道具的纯函数   州;构造函数的副作用是反模式,但可以移动   到componentWillMount

我的浏览器进入无限循环并崩溃

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

你可以从这一行看到,

https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/NavLink.js#L34

isActive呈现函数中立即调用在NavLink上传入的函数。

setState显然不应该在render中使用,因为这可能导致无限渲染循环。

您应该使用componentWillReceiveProps代替。