我希望这个标题是有意义的,但是这个React生命周期方法本质上是相当令人困惑的。
我不能重新渲染新组件,因为之前的道具改变了。(道具。error is NOT undefined)
解释- 一旦在componentDidMount中出现错误,props。错误变为'STRING'
- 第一次,它
goBack()
和工作正常。 - 第二次,但是当我们再次打开这个组件时,因为props。错误是字符串(不是未定义的),它不渲染和返回,
我如何使它呈现组件?
static getDerivedStateFromProps(props: Props, state: State): State | null {
const {
error,
} = props;
// Once error is occured in componentDidMount, props.error is not undefined.
// First time, it works and go back to the previous page.
// But when we open this component again, it doesn't render and go back, because props.error is NOT undefined.
// componentDidMount still gets triggered to fetch, but it gets triggers AFTER this
if (error) {
goBack(); //// I MUST call this (This hide or unmount the current component)
}
...
}
componentDidMount() {
fetch() // this causes an error and update props.error (from undefined to 'STRING')
}
调用goBack
时清除父组件的error
状态