[英]How do I set the state of a parent component in a child component using an onClick function?
I will only show code that is relevant.我只会显示相关的代码。 This is the code from the
parent component
:这是
parent component
的代码:
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
activeScreen: 'dashboard',
authenticatedUser: this.getAuthenticatedUser(),
}
}
setActiveScreen(key) {
this.setState({
activeScreen: key
})
}
style = (label) => {
if (label === 'Dashboard') {
return {'border-top': '5px solid red'}
}
}
render() {
return (
<div>
{/* {this.serviceWorker()} */}
<ToastContainer transition={Slide} />
<Router>
<Switch>
<NavBar
authenticatedUser={this.state.authenticatedUser} activeScreen={this.state.activeScreen}
setActiveScreen={this.setActiveScreen()} />
</Switch>
</Router>
</div>
);
}
} }
The code from the child component Navbar
is:子组件
Navbar
的代码是:
class NavBar extends Component {
constructor(props) {
super(props);
}
adminMenu() {
return (
<div className='admin-menu'>
{this.adminNav().map((i, key) => (
<li className="nav-item" style={this.props.style(i.label)} key={key}>
<Link className={`nav-link ${this.props.activeScreen == i.key ? 'active' : ''}`} to={i.to} onClick={() => this.props.setActiveScreen(i.key)}>
<i className={`fa fa-fw fa-${i.icon}`} aria-hidden="true"></i>
{i.label}
{this.props.activeScreen == i.key &&
<span className="sr-only">(current)</span>
}
</Link>
</li>
))}
</div>
)
}
render() {
return (
{this.adminMenu()}
);
}
adminNav() {
return [
{
label: 'Dashboard',
icon: 'tachometer',
key: 'dashboard',
to: '/',
active: true,
admin: false,
sales: false
},
there are more of these objects
]
}
}
export default NavBar;
The error I get is Cannot update during an existing state transition (such as within render
or another component's constructor).我得到的错误是无法在现有状态转换期间更新(例如在
render
或其他组件的构造函数中)。 Render methods should be a pure function of props and state; Render 方法应该是 props 和 state 的纯函数; constructor side-effects are an anti-pattern, but can be moved to
componentWillMount
.构造函数的副作用是一种反模式,但可以移动到
componentWillMount
。 The stack trace says it is in setActiveScreen
.堆栈跟踪说它在
setActiveScreen
。 I am unable to fix this problem.我无法解决这个问题。
My syntax is all fine but may not seem so as I have deleted lots of unrelated code.我的语法都很好,但可能看起来不像,因为我删除了很多不相关的代码。
You are invoking the function with no parameters.您正在调用没有参数的函数。 Update your code with this;
用这个更新你的代码;
setActiveScreen={this.setActiveScreen}
OR或者
setActiveScreen={(key) => this.setActiveScreen(key)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.