gpt4 book ai didi

javascript - 设置状态(...): Can only update a mounted or mounting component even if component is mounted

转载 作者:行者123 更新时间:2023-11-28 03:57:17 26 4
gpt4 key购买 nike

我正在使用React最新版本,当单击运行expandMenu()的按钮时,我收到以下错误

这里跟踪生命周期:

constructor
componentWillMount
render
componentDidMount
componentWillReceiveProps
render
componentWillReceiveProps
render
componentWillReceiveProps
render
expandMenu <<< click on the button - boom error!

据我所知,该组件是在运行expandMenu()时安装的,这使得错误不明确。什么可能导致该问题以及如何解决它?

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted

export class Menu extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
showPath: true,
selectedItemIdx: 1,
}
}

componentWillReceiveProps(nextProps: Props) {
const { items } = nextProps
this.setState({
selectedItemIdx: items.length - 1,
})
}

componentWillMount() {
console.debug('componentWillMount')
}

componentDidMount() {
console.debug('componentDidMount')
}

componentWillUnmount() {
console.debug('componentWillUnmount')
}

expandMenu = () => {
console.debug('expandMenu')
const { items } = this.props
if (items.length > 1) {
this.setState({ showPath: true }) // error here
}
}

itemClickHandler = (idx: number) => {
this.expandMenu()
}

render() {
console.debug('render')
const { classes } = this.props
return (
<div className={classes.root}>
<ButtonBase
className={classes.title}
onClick={() => {
this.itemClickHandler(idx)
}}
>
))}

</div>
)
}
}

最佳答案

问题与 react-hot-loader 有关,我必须将其从我的项目依赖项中删除。

关于javascript - 设置状态(...): Can only update a mounted or mounting component even if component is mounted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47472357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com