在react+antd的前端开发中少不了使用Modal+Form的形式来实现添加/编辑等功能!
本文主要记录在使用antd4.9.2开发过程中经常遇到的问题:this.formRef.current为空的情况!
首先需要验证一个机制就是当Modal默认visible=false的时候不会去渲染Modal下的组件
class Test extends Component{
constructor(props) {
super(props);
this.formRef = React.createRef()
this.state = { show: false}
console.log('Test.constructor')
}
render() {
return (
<Modal visible={this.state.show}>
<Home/>
<Form ref={this.formRef}>
</Form>
</Modal>)
}
}
class Home extends Component{
constructor(props) {
super(props);
console.log('Home.constructor ')
}
render() {
return (
<div>hello world!</div>)
}
}
}
上述代码默认Modal是不显示的,第一次运行的时候console打印日志为
Test.constructor
当默认Modal为显示的时候,第一次运行的时候console打印日志为
Test.constructor
Home.constructor
所以很多时候需要在componentWillReceiveProps中对Form表单进行操作比如重置表单默认数据时,很可能会因为this.formRef.current还没有被初始化而导致的异常,代码如下
componentWillReceiveProps(nextProps) {
this.formRef.current.resetFields();
}
解决方案如下代码,在setState()的回调函数中去操作,setState的回调函数表示已经执行了render完毕,所以这时this.formRef.current肯定是初始化过了的
componentWillReceiveProps(nextProps) {
this.setState({
show: nextProps.show,
value: nextProps.value
},
() => {
if(this.formRef.current)
{
this.formRef.current.resetFields();
}
})
}