我是新来的反应者,我正在尝试从API提取数据并将数据传递给子组件。我已经将数据传递给父组件的状态,但是当我将其作为道具传递给子组件时,它会记录为一个空数组。我确定有一些简单的事情我可以忽略,但是我不知道是什么,我的代码在下面
父项
import React, {Component} from 'react';
import Child from '../src/child';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
properties: []
}
}
getData = () => {
fetch('url')
.then(response => {
return response.text()
})
.then(xml => {
return new DOMParser().parseFromString(xml, "application/xml")
})
.then(data => {
const propList = data.getElementsByTagName("propertyname");
const latitude = data.getElementsByTagName("latitude");
const longitude = data.getElementsByTagName("longitude");
var allProps = [];
for (let i=0; i<propList.length; i++) {
allProps.push({
name: propList[i].textContent,
lat: parseFloat(latitude[i].textContent),
lng: parseFloat(longitude[i].textContent)
});
}
this.setState({properties: allProps});
});
}
componentDidMount = () => this.getData();
render () {
return (
<div>
<Child data={this.state.properties} />
</div>
)
}
}
export default App;
儿童组件
import React, {Component} from 'react';
class Child extends Component {
initChild = () => {
console.log(this.props.data); // returns empty array
const properties = this.props.data.map(property => [property.name, property.lat, property.lng]);
}
componentDidMount = () => this.initChild();
render () {
return (
<div>Test</div>
)
}
}
export default Child;
答案 0 :(得分:2)
将子级中的componentDidMount更改为componentDidUpdate。
componentDidMount生命周期方法在开始时仅被调用一次。而只要应用程序状态发生变化,就会调用componentDidUpdate生命周期方法。由于api调用是异步的,因此在将api调用的结果传递给子级之前,initChild()函数已经被调用一次。
答案 1 :(得分:0)
您可以使用条件渲染
import React, {Component} from 'react';
class Child extends Component {
initChild = () => {
if(this.props.data){
const properties = this.props.data.map(property => [property.name, property.lat, property.lng]);
}
}
componentDidMount = () => this.initChild();
render () {
return (
<div>Test</div>
)
}
}
export default Child;
答案 2 :(得分:0)
如果您使用的是基于类的组件,请使用componentDidUpdate方法
componentDidUpdate() {
console.log(props.data);
//Update child component state with props.data
}
如果您正在使用功能组件,请使用useEffect
useEffect(() => {
console.log(props.data);
//Update child component state with props.data
}, []);