状态已显示为已更新为组件中的新值WillReceiveProps.现在有没有办法检查道具的变化?



当组件从其父组件接收新 props 时,我正在尝试调用一个函数。

我正在像这样componentWillReceiveProps检查它

componentWillReceiveProps(nextProps){
console.log('props urls length :',  nextProps.urls.length);
console.log('state urls length :',  this.state.urls.length);
if(nextProps.urls.length!= this.state.urls.length){
console.log('new props in canvas in IF :',nextProps.urls);
let urls = this.props.urls;
let urlsOrder = [];
urls.map((item)=>{
let newItem = item.replace('http://172.104.60.70/st_old/uploads/tripdoc/split/','');
if(nextProps.type === 'maildoc'||nextProps.type==='itinerary'||nextProps.item && nextProps.item.doctype === 'important' && nextProps.doctypes && nextProps.item.doctypes === 'emaildoc'){
newItem = item.replace(' http://172.104.60.70/st_old/uploads/maildoc/split','');
}else if(nextProps.type === 'agency'){
newItem = item.replace('http://172.104.60.70/st_old/uploads/defaultdocs/7/split','');
}else if(nextProps.type === 'clients'){
newItem = item.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split','');
}
urlsOrder.push(newItem);
});
this.setState({
urlsOrder,
urls:nextProps.urls
});
this.pdfConversion(nextProps.urls);
setTimeout(nextProps.hideLoading(),2000);
}
}

问题是在这些控制台日志中,我可以清楚地看到值是相同的

console.log('props urls length :',  nextProps.urls.length);
console.log('state urls length :',  this.state.urls.length);

因此,我放置的支票不起作用,并且不会进入if语句。

我尝试使用derivedStateFromProps,这也显示了类似的东西。

值相同,因此检查在那里也不起作用。 我的意思是显然 props 会改变,因为父组件正在发送新更新的数据,但是为什么这个子组件中的状态会自动改变?

请告诉我哪里出错了??

假设这就是它应该如何表现,那么请告诉我当道具或状态发生变化时如何调用某个函数?

这是我在组件中尝试的方式DidUpdate

componentDidUpdate(prevProps,prevState){
console.log('prevProps',prevProps);
console.log('prevstate : ',prevState.urls.length);
console.log('new props in canvas :',this.props.urls.length);
if(prevState.urls.length!= this.props.urls.length){
console.log('new props in canvas in IF :',this.props.urls);
let urls = this.props.urls;
let urlsOrder = [];
urls.map((item)=>{
let newItem = item.replace('http://172.104.60.70/st_old/uploads/tripdoc/split/','');
if(this.props.type === 'maildoc'||this.props.type==='itinerary'||this.props.item && this.props.item.doctype === 'important' && this.props.item.doctypes && this.props.item.doctypes === 'emaildoc'){
newItem = item.replace(' http://172.104.60.70/st_old/uploads/maildoc/split','');
}else if(this.props.type === 'agency'){
newItem = item.replace('http://172.104.60.70/st_old/uploads/defaultdocs/7/split','');
}else if(this.props.type === 'clients'){
newItem = item.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split','');
}
urlsOrder.push(newItem);
});
this.setState({
urlsOrder,
urls:this.props.urls
});
this.pdfConversion(this.props.urls);
}
}

当组件从其父级收到新 props 时,我正在尝试调用一个函数。

这自然地导致渲染(更新(。尝试使用componentDidUpdate(prevProps, prevState, snapshot)

componentDidUpdate(( 在更新发生后立即调用。 初始呈现不调用此方法。

您有一个明确的机会来比较此生命周期钩子中的this.propsprevProps,以及this.stateprevState

还值得一提的是,componentWillReceiveProps将在未来的版本中弃用

相关内容

最新更新