React 踩坑 使用useState改变值之后拿不到值的问题??

        最近在项目中发现了一个问题,在使用useState修改值之后,拿不到修改后的值,能肯定的是肯定修改了,不然页面会空白,但是拿不到数据,就很无奈。

        最后发现,函数式组件使用useState设置值的方法也是一个异步的方法,而直接输出是同步的,但是还是拿不到值

        这个加上await之后保证fectchData函数执行完成之后在输出,应该就会有值,但是输出还是{}

       无奈发现,useEffect里面的立即执行函数只会执行一次,因为第二个参数是空数组,导致它没有监听任何数据的值,就相当于类式组件中的componentDidMount钩子,因此只会执行一次

修改代码为:

  useEffect( () => {
      fetchData()
    },[])

    useEffect(() => {
      // 监听cityArr的值,第一次肯定为{},等到它有数据之后,在输出
      if(Object.keys(cityArr).length !== 0){
        console.log(cityArr);
        listRef.current.measureAllRows()
      }
    },[cityArr])

 如此,就解决了拿不到数据的问题

### React `useState` Hook Set Method Not Working Solutions and Troubleshooting In React applications, encountering issues where the `setState` function from the `useState` hook does not seem to update state as expected can lead to confusion. This problem might arise due to several common pitfalls. #### Understanding Asynchronous Nature of State Updates State updates may be batched by React for performance optimization; therefore, they do not immediately reflect changes when called within event handlers or lifecycle methods[^3]. To ensure correct behavior after a state change: ```javascript import React, { useState } from 'react'; function ExampleComponent() { const [count, setCount] = useState(0); const handleClick = () => { setCount(prevCount => prevCount + 1); console.log(count); // May log previous value because setState is asynchronous. }; useEffect(() => { console.log(`Updated count: ${count}`); }, [count]); return ( <button onClick={handleClick}> Click me </button> ); } ``` #### Avoiding Direct Mutation of State Objects Directly mutating objects or arrays stored in state without using functional updates can cause unexpected behaviors since it bypasses re-render triggers provided by React's reconciliation process[^4]. For instance, consider an array inside state being modified directly versus immutably updating its contents through spreading or utility libraries like Immer.js: ```javascript // Incorrect approach (direct mutation) const handleAddItemIncorrect = newItem => { let newList = items; newList.
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值