为了让我的
parent component
(JsonFetcher
)访问我的child component
(Display
)中的值,我尝试使用刚刚来自此补丁16.3的createRef()
API
按照本文档中的“向类组件添加引用”示例,以下是我在代码中尝试的内容:
class JsonFetcher extends Component {
constructor(props) {
super(props);
this.child = React.createRef();
this.state = {
data: [],
}
}
componentDidMount() {
this.updateContent(this.props.mainUrl)
}
updateContent(mainUrl){
fetch(mainUrl)
.then((responseJsonAnyUrl) => responseJsonAnyUrl.json())
.then((responseJsonAnyUrl) => {
this.setState({
mainUrl: mainUrl,
jsonObject: responseJsonAnyUrl
},
function () {
this.timeout = setTimeout(
function(){
//let ind = this.child.current.getCurrentIndex
//tyring to get values from child...
//if index === length-1
this.updateContent(mainUrl)
//else
//retry this function in 5 seconds
//
}.bind(this, mainUrl)
,
20000)
}.bind(this))
})
}
interpretJson() {
/*
*some code
*/
return(
<Display content={contentListArray} ref={this.child}/>
)
}
render() {
if(this.state.jsonObject){
return (
<div>
<div> {this.interpretJson()} </div>
</div>
)
}else
return(
null
)
}
}
所以,我在构造函数中创建了
ref
,将其链接到child component
方法末尾的Display
interpretJson()
,然后我尝试在我的timeOut()
函数中使用子方法。但是我收到以下错误:
“类型错误:无法读取 null 的属性‘getCurrentIndex’”
我做错了什么,不让我调用子方法,以便我可以模拟我评论过的伪代码?
(编辑)注释:
我的子组件
Display
不是无状态组件,它是一个
班级。 我已经尝试在渲染中调用
<Display>
,但是使用箭头函数将此方法绑定到类。这样,this.child
中的
this就会绑定到类组件
interpretJson = () => {
/*
*some code
*/
return(
<Display content={contentListArray} ref={this.child}/>
)
}
如果上述答案不起作用,请执行此操作
constructor(props) {
super(props);
this.interpretJson = this.interpretJson.bind(this);//bind function to class
this.child = React.createRef();
this.state = {
data: [],
}
}
interpretJson() {
/*
*some code
*/
return(
<Display content={contentListArray} ref={this.child}/>
)
}
我也遇到了这个问题(我使用的是typescript)
private modal = React.createRef<HTMLDivElement>()
// ...
public componentDidMount() {
console.log(this.modal)
}
// ...
public render() {
// ...
<div ref={this.modal} className="modal fade"
// ...
输出。从一开始就是空的,然后在一段时间后填充:
问题是在渲染方法中我提前退出,并且未到达参考代码
public render() {
const { data } = this.state
// here we return early, ref bellow is not reached
// and in componentDidmount we can't rely on this.modal.current
// this.modal.current will be populated only if data is not null
if (data === null) { return null }
return (
<div ref={this.modal} className="modal fade"
// ...