[英]react useEffect with function received as props from parent component
[英]Wait for react props received from parent to update inside a childs function
我有一個在 componentDidMount() 中執行的函數,因為它執行 API 調用,我需要為渲染接收到的信息。
componentDidMount() {
this.setState({
email: this.props.email
});
this.getPermissionsList();
this.getPermissionsValue(); //this one
}
現在,這個函數有以下問題
getPermissionsValue(){
console.log('/user/'+this.props.userId+'/permission') //At the moment of the execution, this.props.userId is empty
API.get('/user'+this.props.userId+'/permission')
.then(response => {
console.log(response)
this.setState({
permissionValue : response.data
}, () => {
console.log(this.state.permissionValue)
});
})
}
但是在我的渲染中,我可以看到 this.props.userId 值。
render(){
return <p>{this.props.userId}</p>
}
在渲染之前如何等待該道具?
編輯:這就是道具從父級發送給子級的方式
在父組件中,我在渲染中有一個子組件
<EditUserModal ...a lot of props.... userId={this.state.rowId} email={this.state.selectedMail} handleChangePass={this.handleChangePass} ....more props..../>
該 rowId 在父組件中以這種方式分配:
在我的渲染中,我有這個
<Table
className="table"
filterable={['Email']}
itemsPerPage={8}
currentPage={0}
sortable={true}
>
{users.map((row) => {
return (
<Tr className={row.className}>
<Td column="Email">{row.email}</Td>
<Td column="Edit" ><FontAwesomeIcon className="editIcon" onClick={()=> this.showModal(row.id, row.email)} icon={faEdit} /></Td>
</Tr>
)
})}
</Table>
onclick 調用的地方
showModal(rowId, rowEmail) {
this.setState({
showModal: true,
rowId: rowId,
selectedMail: rowEmail
}, () => {
// console.log("clicked show modal")
// console.log(this.state.showModal)
});
}
這就是設置 rowId 狀態值的地方
在您的場景中,我認為您的子組件中的componentDidMount
很有可能在this.props.userId
獲得值之前this.props.userId
。 (我認為您的user
數組也來自 API 調用)。 您可以查看此線程中的討論以了解為什么會發生這種情況。
我的建議是,不要把 API 調用放在componentDidMount()
,而是放在componentDidUpdate()
,如果你做比較,你就不用擔心多次調用 API 了。 這是官方文檔中推薦的典型用法
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
yourAPI(this.props.userID);
}
}
這里也是我在嘗試比較部署 API 調用的位置之前寫的一個答案。
您可以使用 setState 的第二個參數:
componentDidMount() {
this.setState({
email: this.props.email
}, () => {
this.getPermissionsList();
this.getPermissionsValue(); //this one
});
}
這確保首先設置狀態,然后調用其他兩個方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.