最新バージョンのreactを使用していますが、実行中のボタンをクリックすると次のエラーが発生します expandMenu()
ここでライフサイクルをトレースします。
constructor
componentWillMount
render
componentDidMount
componentWillReceiveProps
render
componentWillReceiveProps
render
componentWillReceiveProps
render
expandMenu <<< click on the button - boom error!
AFAIKは、実行時にコンポーネントがマウントされるexpandMenu()
ため、エラーがあいまいになります。何が問題を引き起こし、どのように修正するのですか?
setState(...):マウントされたコンポーネントまたはマウントされたコンポーネントのみを更新できます。これは通常、マウントされていない状態でsetState()を呼び出したことを意味します
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
、プロジェクトの依存関係から削除する必要があることに関連していました。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加