[英]how to set react parent component state by a async function and then pass this state to child as props?
[英]How to pass async state to child component props?
我是新手,我正在嘗試從 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;
將 child 中的 componentDidMount 更改為 componentDidUpdate。
componentDidMount 生命周期方法在開始時只調用一次。 而只要應用程序的狀態發生變化,就會調用 componentDidUpdate 生命周期方法。 由於 api 調用是異步的,initChild() 函數在 api 調用的結果傳遞給子進程之前已經調用了一次。
您可以使用條件渲染
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;
如果您使用的是基於類的組件,請使用 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
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.