【问题标题】:Cannot set state to location.pathname in React Router V4无法在 React Router V4 中将状态设置为 location.pathname
【发布时间】:2017-11-16 13:38:00
【问题描述】:

我正在尝试将组件的状态设置为 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 或其他组件的 构造函数)。渲染方法应该是 props 的纯函数和 状态;构造函数副作用是一种反模式,但可以移动 到componentWillMount

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

有什么想法吗?

【问题讨论】:

标签: reactjs react-router-v4


【解决方案1】:

从这一行可以看出,

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

isActive 上传入的函数会立即在 NavLink 渲染函数中调用。

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

您应该改用componentWillReceiveProps

【讨论】:

  • 谢谢!对我来说最简单的解决方案是将状态始终设置为 this.location.pathname。但是,我不知何故无法访问我的组件中的该属性
  • 似乎问题在于我的 ResponsiveDrawer 组件超出了 范围,因此我无法访问 this.props.params.match。有没有办法解决这个问题?
  • window.location 似乎可以工作,但是当我单击新组件时它不会更新。理想情况下,我想要类似于订阅您可能从 Angular 中知道的路由器更改的东西
猜你喜欢
  • 2018-02-28
  • 2022-01-24
  • 2018-01-29
  • 1970-01-01
  • 2020-07-09
  • 2017-08-16
  • 2018-12-27
  • 2017-10-26
  • 1970-01-01
相关资源
最近更新 更多