无法从渲染方法React更新状态

时间:2017-11-17 16:03:58

标签: reactjs react-router

我有一个这样的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或其他组件的构造函数中)。渲染方法   应该是道具和国家的纯粹功能;构造函数的副作用   是一种反模式,但可以移到componentWillMount

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

2 个答案:

答案 0 :(得分:1)

如果&#34;状态&#34;你已经在React Router中,然后将它复制到你自己的状态是不必要的重复,以及你的错误原因(试图在render期间更新状态。你最好只是从React Router获取状态。你可以使用没有路径的路径

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

答案 1 :(得分:0)

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

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

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