【问题标题】:Cannot update state from render method React无法从渲染方法 React 更新状态
【发布时间】:2018-05-01 11:18:05
【问题描述】:

我有一个这样的 NavLink 组件:

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

并尝试在每次 NavLink 处于活动状态时设置我的状态,如下所示:

 updateActivePath = (match) => {
    if (match && this.state.activePath !== match.path) {
      this.setState({activePath: match.path})
    }
  };

  isActiveFunc = (match, location) => {
    this.updateActivePath(match);
  };

然而,这给了我以下错误:

警告:在现有状态转换期间无法更新(例如 在render 或其他组件的构造函数中)。渲染方法 应该是 props 和 state 的纯函数;构造函数副作用 是反模式,但可以移动到componentWillMount

有什么办法可以解决这个问题吗?

【问题讨论】:

  • 是 react-router 的 NavLink 吗?
  • 来自 react-router-dom
  • 为什么要将活动路径复制到本地状态?只需从 react-router-dom 中获取活动路径
  • 这似乎不起作用,因为我的组件不在 中(它是始终显示的导航栏)

标签: reactjs react-router


【解决方案1】:

您在反应生命周期中使用 setState。您在渲染或其他生命周期方法反应中调用您的方法 updateActivePath。这会为您的组件触发额外的渲染。

要修复此警告,请更改您在 componentWillMount 方法或函数调用中的 setState 位置(单击、...)。

有关必须信息,请访问生命周期组件文档:https://reactjs.org/docs/react-component.html

【讨论】:

  • 如何获取到 componentWillMount 的当前路由器路径?
  • 看起来 withRouter 是答案,但它似乎在 v4 中被贬低了
  • 您可以在构造函数中获取当前路由器,也可以使用 React-redux 创建路由器商店。在这个商店中,您可以存储许多信息(currentRoute、previousRoute、...),并且您可以在 NavLink 组件中获取这些信息。
【解决方案2】:

如果您所追求的“状态”已经在 React Router 中,那么将其复制到您自己的状态是不必要的重复,并且是导致错误的原因(尝试在 render 期间更新状态。你最好只是从 React 路由器中获取状态。你可以使用没有路径的 Route

<Route render={({ location }) => (
   // this will render whenever the location changes
   <YourNavigationBar location={location} />
  )}
/>

【讨论】:

  • 这似乎做到了!非常感谢您的建议。
猜你喜欢
  • 2018-04-12
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2016-11-04
  • 1970-01-01
相关资源
最近更新 更多