【发布时间】: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。
我的浏览器进入无限循环并崩溃
有什么想法吗?
【问题讨论】:
-
我们能看到
NavLink组件吗,看起来它正在立即调用isActive属性上传入的函数?