antd中this.formRef.current为空的问题

react+antd的开发过程中经常会用到Modal+Form的组合来实现新增、编辑的功能。使用过程中常会遇到this.formRef.current为空的问题。

查阅资料后了解到这是由于Modal组件在visiblefalse时,内部组件不会渲染导致的。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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>)
}
}
}

该代码首次渲染时只会打印Test.constructor,意味着Home组件没有被渲染出来。
而展示Modal组件后,就会打印Home.constructor。所以在Modal组件不可见时,是获取不到this.formRef.current的。进而导致很多时候需要在componentWillReceiveProps中对 Form 表单进行操作,例如重置表单默认数据时,因为this.formRef.current还没有被初始化而导致异常。

  • 解决方案
    setState()的回调函数中去操作。
    setState 的回调函数是在 render 完成后调用的,所以这时this.formRef.current肯定是有内容的。
1
2
3
4
5
6
7
8
9
10
componentWillReceiveProps(nextProps) {
this.setState({
show: nextProps.show,
value: nextProps.value
}, () => {
if(this.formRef.current) {
this.formRef.current.resetFields();
}
})
}