[英]Trouble passing props to componentDidMount in child component (React)
[英]React axios request in ComponentDidMount not passing data as props to component
大家好,我在這里看不到我的錯誤,希望有人可以幫助...這是我的 fetch Data 類:
export default class Auftrag extends Component {
state = {
auftraege: "Test",
};
getAuftraege = () => {
axios.get("Auftraege/auftraege").then(e => {
this.setState({
auftraege: e.data,
});
console.log(e.data);
});
};
componentDidMount() {
this.getAuftraege();
}
render() {
return (
<>
<AuftragDisplay test={this.state.auftraege} ></AuftragDisplay>
</>
);
}
}
這是我的 Display 類中的構造函數:
constructor(props) {
super(props);
console.log(props);
}
axios 請求被觸發,我在控制台中獲得了正確的數據。 但它沒有傳遞給我的組件。 希望有人知道出了什么問題並可以幫助我
已解決:謝謝 san 我試過了,可以解決問題。 我得到了數據,但是在更新之前調用了 console.log() 所以我得到了舊數據。 再次感謝
你的代碼看起來不錯。 您可以在下面看到具有不同 api 的相同代碼作為示例
class Auftrag extends Component {
state = {
auftraege: "Test",
};
getAuftraege = () => {
axios
.get("https://jsonplaceholder.typicode.com/posts/1")
.then(e => this.setState({auftraege: e.data}))
};
componentDidMount() {
this.getAuftraege();
}
render() {
return (
<>
<AuftragDisplay test={this.state.auftraege} ></AuftragDisplay>
</>
);
}
}
const AuftragDisplay = ({test}) =><h2>Hi--->{test.title}</h2>
只需將狀態放在 Auftrag 類的構造函數中,我就應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.