ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

formRef=React.createRef() this.formRef.current为null

2022-01-27 11:03:06  阅读:210  来源: 互联网

标签:current 组件 Form formRef React ggxhs ggxhForm createRef


情景说明:

      做一个商品查看的页面,商品信息回显,使用的antd,部分代码如下:

.......

export default class GoodsDetail extends React.Component{ 
	ggxhForm = React.createRef();
	constructor(props) {
	    super(props)
		this.state={
			....
			ggxhs:[],
		}
	}
	componentDidMount(){
		service.post(.....).then(res => {
			if (res.data.code === '0000') {
			    this.setState({
                    .....
					ggxhs:res.data.data.ggxhs
				},()=>{
					setTimeout(() => {
					     console.log(this.ggxhForm);
					 }, 100);
				
				})
			}
		})
	}

	render(){
		return (
		    <div className={gdetail.container}>
                ......
			<Row> 
			   <Skeleton>	
				   <Form name="hhhhh"
				         layout="vertical"
						 ref={this.ggxhForm}
						 initialValues={{"ggxhs": this.state.ggxhs}}>
				   		    ......
				   		</Form>
			      </Skeleton>
			</Row>
		</div>
		)
	}
	
}

上面的代码中再构造函数之前,我创建了  ggxhForm 利用的是 React.createRef() 然后再render 函数中Form 中也关联使用了 ref={this.ggxhForm}  然后我在生命周期函数 componentDidMount 中通过Axios 请求后他的接口,在返回的信息中调用this.setState({}) 这个方法,并且在this.setState({})回调函数中去执行resetFileds() 提示 undefined properties "resetFieds" of null 

由此可以判断的是this.ggxhForm.current:null

那么为什么会这样

分析:  在网上我也找了很多的例子,有的说 1. componentDidMount  执行的时候有些form组件还没有被渲染,所有在使用this.ggxhForm.current的可以延迟执行

    setTimeout(() => {
                         console.log(this.ggxhForm);
   }, 100);

可是还是没有解决

然后我想会不会和 <Skeleton></Skeleton>这个组件有一定的关系

这个组件是占位置的组件,脚骨架

果不其然

            <Skeleton loading={this.state.isLoading}>	
				   <Form name="hhhhh"
				         layout="vertical"
						 ref={this.ggxhForm}
						 initialValues={{"ggxhs": this.state.ggxhs}}>
				             .......
				   		</Form>
			      </Skeleton>

里面的loading 如果为true 就会一直的加载,那么里面Form 就不会被初始化

所以解决办法在于,调用成功后台接口之后,将loading 的属性设置为 false

 总结原因是其他的组件影响了Form的初始化(Skeleton   影响了 Form的初始化)

希望对你有所帮助

标签:current,组件,Form,formRef,React,ggxhs,ggxhForm,createRef
来源: https://blog.csdn.net/datouniao1/article/details/122713338

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有