【发布时间】:2021-01-07 20:57:38
【问题描述】:
我有一个组件,它接受一个 Id 道具并使用它来进行一些 fetch 调用以填充自身等。这个 id 可以更改或为空,因此该组件应该能够重新获取并在它有任何需要时执行它需要的任何操作这些值。当组件首次渲染时,id 始终为空,但如果/当它发生更改时,组件构造函数或componentDidMount() 函数永远不会被调用,当我尝试将其更改为componentDidUpdate() 并手动检查值何时更改时,它甚至从来没有用新的 id 来调用它。
我有以下外部类(高度简化),它调用 EligibilityCard 组件并传递 id:
class ActionsTab extends React.Component{
render(){
let playerId = null;
if(this.props.data && this.props.data.playerId){
let playerId = this.props.data.playerId;
}
return(
<EligibilityCard playerId={playerId}/>
)
}
}
还有组件本身(也简化了):
class EligibilityCard extends React.Component{
componentDidMount(){
const requestData = {event: this.props.event.id};
if(this.props.playerId){
requestData.playerId = this.props.playerId;
}
$.ajax(path and requestData){
...
}
}
}
编辑:针对某些 cmets,我尝试将 EligibilityCard.componentDidMount() 更改为此,它只打印了 null:
class EligibilityCard extends React.Component{
componentDidUpdate(){
console.log(this.props.playerId);
在ActionsTab.render() 的return 行和componentDidMount/Update 的第一行使用带有断点的chrome 调试器:render 被多次调用,最初是playerId=null,最后是playerId=somenumber。 componentDidMount 断点通过props.playerId=null 到达几次,因为页面的各种元素加载和屏幕重新渲染,但到渲染函数中的 id 更改时,componentDidUpdate 不再被调用
【问题讨论】:
-
这就是它应该如何工作的。更改的道具不会重新安装组件,只会重新渲染。
-
@BrianThompson 是正确的。使用类组件,您可以使用
componentDidUpdate在重新渲染后运行逻辑。 -
正如我在问题本身中所说,我尝试了
componentDidUpdate,但从未使用新 ID 调用它。 -
请edit 你的问题显示哪个类有
componentDidUpdate()方法。并展示playerId的变化。 -
是的,我们需要看到更大的上下文。无论是渲染
ActionsTab都可能没有正确执行。重要的原因是因为ActionTab确实从父母那里得到this.props.data.playerId,因此该道具的成功通过在这里也很重要。您有机会在 CodeSandbox.io 中编写一个基本的可重现示例吗?
标签: reactjs