【问题标题】:React Hooks unable to update stateReact Hooks 无法更新状态
【发布时间】:2020-11-10 09:07:04
【问题描述】:

我正在尝试从 API 响应中更新状态。从 API 获取响应,但它没有更新到状态。我尝试将 useEffect 作为 componentDidUpdate,但组件正在连续呈现。我只想渲染一次。 下面是代码截图,

// I want to update to lookup data
 const [lookUpData, setLookUpdata] = useState({
    BlueLaws: [],
    Departments: [],
    ProdCodes: [],
    Fees: [],
    IdChecks: [],
    IndustryStandards: [],
    Tax: []
  })
// calling getLookUpdata from useEffect()
useEffect(() => {
    getLookUpdata();
  }, []);

// Defination of getLookUpdata method
const getLookUpdata = () => {
    var postData = {};
    postData.storeID = "xxxx";
    postData.posType = 0;
    axios.post(url, postData).then(res => {
      if (res.status === 200 && res.data.response && res.data.response.length > 0) {
       res.data.response[0].blueLaws.length > 0 && setLookUpdata({ ...lookUpData, BlueLaws: res.data.response[0].blueLaws[0].blueLaws })
        res.data.response[0].departments.length > 0 && setLookUpdata({ ...lookUpData, Departments: res.data.response[0].departments[0].departments })
        res.data.response[0].departments.length > 0 && setLookUpdata({ ...lookUpData, ProdCodes: res.data.response[0].departments[0].prodCodes })
        res.data.response[0].fees.length > 0 && setLookUpdata({ ...lookUpData, Fees: res.data.response[0].fees[0] })
        res.data.response[0].idChecks.length > 0 && setLookUpdata({ ...lookUpData, IdChecks: res.data.response[0].idChecks[0].ageValidations })
        res.data.response[0].industryStandards.length > 0 && setLookUpdata({ ...lookUpData, IndustryStandards: res.data.response[0].industryStandards[0].industryStandards })
        res.data.response[0].tax.length > 0 && setLookUpdata({ ...lookUpData, Tax: res.data.response[0].tax[0].taxRates })
      } else if (res.status === 409) {
        console.log(res.data.error)
      }
    }).catch(err => {
      console.log(err);
    })

  }

【问题讨论】:

  • 如果你不想在数组中传递任何依赖。这意味着它只会在安装组件时运行。由于 api 是异步工作,所以这就是它不在那里更新的原因。在useEffect 中传递依赖项。我建议阅读更多关于useEffect

标签: reactjs react-hooks use-effect use-state


【解决方案1】:

确保您调用的是正确的嵌套数组和对象(您需要 data.response[0] 吗?...等等..),如果可以,请尝试以下操作:

// I want to update to lookup data
  const [lookUpData, setLookUpdata] = useState({
    BlueLaws: [],
    Departments: [],
    ProdCodes: [],
    Fees: [],
    IdChecks: [],
    IndustryStandards: [],
    Tax: [],
  });

  // calling getLookUpdata from useEffect()
  useEffect(() => {
    async function getLookUpdata() {
      var postData = {};
      postData.storeID = 'xxxx';
      postData.posType = 0;

      try {
        const {data} = await axios.post(url, postData);
        data.response[0].blueLaws.length > 0 &&
          setLookUpdata({
            ...lookUpData,
            BlueLaws: data.response[0].blueLaws[0].blueLaws,
          });
        data.response[0].departments.length > 0 &&
          setLookUpdata({
            ...lookUpData,
            Departments: data.response[0].departments[0].departments,
          });
        data.response[0].departments.length > 0 &&
          setLookUpdata({
            ...lookUpData,
            ProdCodes: data.response[0].departments[0].prodCodes,
          });
        data.response[0].fees.length > 0 &&
          setLookUpdata({
            ...lookUpData,
            Fees: data.response[0].fees[0],
          });
        data.response[0].idChecks.length > 0 &&
          setLookUpdata({
            ...lookUpData,
            IdChecks: data.response[0].idChecks[0].ageValidations,
          });
        data.response[0].industryStandards.length > 0 &&
          setLookUpdata({
            ...lookUpData,
            IndustryStandards:
              data.response[0].industryStandards[0].industryStandards,
          });
        data.response[0].tax.length > 0 &&
          setLookUpdata({
            ...lookUpData,
            Tax: data.response[0].tax[0].taxRates,
          });
      } catch (error) {
        console.log(error);
      }
    }

    getLookUpdata();
  }, []); // <<<< make sure if you will need the dependency

【讨论】:

    【解决方案2】:

    在useEffect代码中:

    useEffect(() => {
        getLookUpdata();
      }, []);
    

    需要在[]数组上声明要观察哪些变量,每次更新都会有组件重新渲染的过程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 2023-03-16
      • 2020-12-28
      • 1970-01-01
      • 2021-07-27
      • 2021-11-13
      相关资源
      最近更新 更多