【问题标题】:State not updating from useEffect hook - Cannot read property 'title' of undefined状态未从 useEffect 挂钩更新 - 无法读取未定义的属性“标题”
【发布时间】:2021-04-29 11:07:05
【问题描述】:

我正在尝试使用 useEffect 更新组件中的状态

 useEffect(() => {
    async function fetchData() {
      let response = await getAccountCoverTypes();
      setData(response);
    }

    fetchData();
  }, []);

我正在设置我的默认值:

  const [data, setData] = useState({
payload: { title: "", accountCoverTypes: [] },

并试图通过数据映射

  const {
    payload: { title, accountCoverTypes },
  } = data;

{accountCoverTypes.map((button, index) => (
      ...
    ))}

当我尝试使用数据时 - 我收到错误,无法读取未定义的属性标题。如何从useEffect 更新状态?

我的服务电话:

const call = async () => {
    try {
        const response = await getItem(xxx);
        return response
}

json 返回:

{
   "payload": {
      "title": "text here",
      "accountCoverTypes": [
         {
            "title": "sample text",
            "details": "sample text",
            "link": "test"
         },..
  
      ]
   }
}

【问题讨论】:

标签: react-native react-hooks


【解决方案1】:

给你一个解决方案

const [data, setData] = useState(null);
useEffect(() => {
  async function fetchData() {
    let response = await getAccountCoverTypes();
    setData(response);
  }

  fetchData();
}, []);



{
  data &&
  data.accountCoverTypes &&
  data.accountCoverTypes.length &&
  data.accountCoverTypes.map((button, index) => (
      ...
))}

在循环或迭代数据变量之前,您应该检查数据是否存在。

【讨论】:

    【解决方案2】:

    好的,当您的函数第一次执行时,数据值将是未定义的,因为您没有为该状态设置任何初始值const [data, setData] = useState()//initial value is not set; 在使用从您的 useEffect 挂钩调用的 setData 函数更新数据的意义上,您的方法是绝对正确的。一旦你的异步函数执行 - 数据将被更新,组件将被重新渲染

    【讨论】:

      【解决方案3】:

      React 依赖于 Hooks 的调用顺序。https://reactjs.org/docs/hooks-rules.html 也就是说useEffect运行后,useState重新初始化数据

      所以将 useState 移到代码中的 useEffect 之前

      const [data, setData] = useState();
      useEffect(() => {
          async function fetchData() {
            let response = await getAccountCoverTypes();
            setData(response);
          }
      
          fetchData();
        }, []);
      

      【讨论】:

        猜你喜欢
        • 2021-12-27
        • 1970-01-01
        • 2019-09-23
        • 2021-02-14
        • 2019-06-08
        • 1970-01-01
        • 2021-03-14
        • 2021-02-14
        • 2020-06-30
        相关资源
        最近更新 更多