我是反应新手,我的一次获取中遇到了问题: 我使用 axios 收到响应,并且响应已格式化。
console.log(formattedResponse) 是一个 jsonObject 但我使用相同的变量设置的状态如下: setSelectedStatParams(formattedResponse) 未定义
我尝试在代码中的另一个地方 console.log 它,但它总是未定义...
我真的不明白为什么..状态 selectedStatParams 在 JSX 中用于地图并且它有效..但是 console.log 始终未定义。
你能帮我理解吗?
提前致谢:)
const handleStatSelection = (statisticId) => {
setIsLoadingStatSelection(true);
axios.get(statsApiUrl + "/filters/" + statisticId)
.then(response => {
const antennaParentSuggIndex = response.data.parentSuggestions.findIndex(parentSugg => parentSugg.parentSuggId === 873);
let formattedResponse = response.data;
formattedResponse.parentSuggestions[antennaParentSuggIndex].childSuggestions = response.data.parentSuggestions[antennaParentSuggIndex].childSuggestions.map((childSugg) => {
//uncheck the unselected Antenna
if (childSugg.value !== auth.antenna) {
childSugg.isActiveCheckBox = 0;
}
return childSugg;
});
setSelectedStatParams(formattedResponse);
console.log(formattedResponse)
console.log(selectedStatParams)
//by default the first result type is the first
if (selectedStatParams?.resultsTypes.length > 0) {
setResultType(selectedStatParams.resultsTypes[0]);
setFixedDate(end);
} else {
setResultType(null);
}
selectedStatParams && fetchStatResult(statisticId)
})
.catch(error => console.error(error))
.finally(() => setIsLoadingStatSelection(false));
};
通过使用useEffect,状态已更新。
const handleStatSelection = (statisticId) => {
setIsLoadingStatSelection(true);
axios.get(statsApiUrl + "/filters/" + statisticId)
.then(response => {
const antennaParentSuggIndex = response.data.parentSuggestions.findIndex(parentSugg => parentSugg.parentSuggId === 873);
let formattedResponse = response.data;
formattedResponse.parentSuggestions[antennaParentSuggIndex].childSuggestions = response.data.parentSuggestions[antennaParentSuggIndex].childSuggestions.map((childSugg) => {
if (childSugg.value !== auth.antenna) {
childSugg.isActiveCheckBox = 0;
}
return childSugg;
});
setSelectedStatParams(formattedResponse);
})
.catch(error => console.error(error))
.finally(() => setIsLoadingStatSelection(false));
};
useEffect(() => {
console.log(selectedStatParams);
if (selectedStatParams?.resultsTypes.length > 0) {
setResultType(selectedStatParams.resultsTypes[0]);
setFixedDate(end);
} else {
setResultType(null);
}
selectedStatParams && fetchStatResult(statisticId);
}, [selectedStatParams]); // Run the effect whenever selectedStatParams changes