gpt4 book ai didi

javascript - 如何更新 componentDidUpdate() 中组件的状态而不陷入无限重新渲染?

转载 作者:行者123 更新时间:2023-12-02 22:19:31 24 4
gpt4 key购买 nike

我有一个带有 componentDidMount() 方法的组件,该方法调用名为 getData() 的方法,该方法获取初始数据并设置组件的初始状态。

class LogsSettings extends React.Component {
constructor(props) {
super(props);

this.settingsUrls = [
"/ui/settings/logging"
];

this.state = {
configSettings: {},
formSchema: formSchema
};

this.configSettings = {};
this.selected = "general";

}

getData = (url, selectedSetting) => {
fetch(url)
.then((response) => {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
response.json().then((response) => {
//pass formschema here
console.log(selectedSetting);
let newFormSchema = this.setNonDefaultValues(response.data, formSchema.subsections);
Object.assign(this.configSettings, response.data);
this.setState({
configSettings : this.configSettings,
formSchema: newFormSchema
});
});
}
)
.catch((err) => {
console.log('Fetch Error :-S', err);
});
};


componentDidMount() {
this.settingsUrls.map((settingUrl) => {
this.getData(settingUrl, this.selected)

})

}

componentDidUpdate() {
this.settingsUrls.map((settingUrl) => {
this.getData(settingUrl, this.props.selectedSetting)

})

}



render() {

return (
<div className="card-wrapper">
<h2>{formSchema.label.toUpperCase()}</h2>
{
formSchema.subsections.map((subSection) => {
return (
<>
<h3>{subSection['description']}</h3>
<div style={{marginBottom: '10px'}}></div>

{
subSection['input_fields'].map((inputField) => {
return buildForm(inputField, this.handleChange)
})
}
<hr></hr>
</>
)
})
}
<button className="button button-primary">Save Changes</button>
</div>
)
}

}

但是,传递给该组件中的 getData() 方法的 selectedSetting 参数将会发生变化,当这种变化时,我需要更改组件的状态,并且获取特定于已更改的 selectedSetting 参数的新数据。

新的 selectedSetting 作为 prop 传递到组件中。问题是,当组件陷入无限循环时,我无法将新的 selectedSetting 参数传递给我的 getData 方法来更新组件的状态。

如何将新的 selectedSetting 传递给 getData() 方法而不陷入无限循环?这可能吗?如果不是,我应该采取的最佳方法是什么?

请注意 selectedSetting 参数尚未在 getData() 函数中使用,但将会用于从 API 调用和新的 API 调用中获取数据表单架构将导致 ConfigSettingsformSchema 状态发生更改

最佳答案

如果您仔细观察组件的生命周期,安装后,您将获取然后更新组件。这将触发 componentDidUpdate 生命周期方法,该方法将执行相同的操作,从而导致无限循环。您需要有一个标志来检查 this.props.selected 是否已更改。如果没有,则不要获取数据,否则将正常获取。在 update 方法中,您可以访问之前的 props。 (您也可以在 componentShouldUpdate 方法中执行此操作,但这将是完全有风险的)

componentDidUpdate(prevProps) {
if( prevProps.selectedSetting !== this.props.selectedSetting ){
this.settingsUrls.map((settingUrl) => {
this.getData(settingUrl, this.props.selectedSetting)
})
}
}

另外,我注意到您的 didMount 方法使用默认的“常规”作为所选设置,因为您希望使用 this.props.selectedSetting 可能会更好,如果它是被使用的,只是将默认 Prop 设置为“常规”。

关于javascript - 如何更新 componentDidUpdate() 中组件的状态而不陷入无限重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59276984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com