axios React state undefined inside a fetch [duplicate]

tvz2xvvm  于 5个月前  发布在  iOS
关注(0)|答案(1)|浏览(43)

此问题在此处已有答案

The useState set method is not reflecting a change immediately(19个答案)
上个月关门了。
我是一个新的React,我有一个问题,在我的一个fetch:我得到的响应与axios和响应的格式。
console.log(formattedResponse)是一个jsonObject,但是我用相同的变量设置的状态如下:setSelectedStatParams(formattedResponse)未定义
我试图在代码中的另一个地方console.log它,但它总是未定义的...
我真的不明白为什么..状态selectedStatParams被用在JSX中的一个Map上,它工作得很好..但是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));
  };

字符串

4ngedf3f

4ngedf3f1#

通过使用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

字符串

相关问题