React useState与定时器一起用,如何解决刷新List属性不显示的问题,请参考,实测可行。

1.useRef 引用定时函数
2. useEffect(() => {
callback.current = callBack;
return () => {};
});
3.setList(oldList=>{
newList=oldList.slice()
//修改属性
return newList
)

import React, {useEffect, useRef, useState} from 'react';

const Test: React.FC = () => {
  const [list, setList] = useState([]);
  const callback: any = useRef();
  const callBack = () => {
      fetch('https://gw.alipayobjects.com/os/bmw-prod/1d565782-dde4-4bb6-8946-ea6a38ccf184.json')
        .then((response) => response.json())
        .then((json) => {
          if(list!=null && list.length>0){
            setList(old=>{  //要页面看到效果,不能用setList(新的值),要用setList(函数)
              let newList=old.slice()
              for(let i=0;i<newList.length;i++){
                newList[i].scales=new Date().toString()
                newList[i].count=new Date().toString()
              }
              return newList
            })
          }
          console.log('value1:',list)
        });
        console.log('value2:',list)

    fetch('https://gw.alipayobjects.com/os/bmw-prod/1d565782-dde4-4bb6-8946-ea6a38ccf184.json')
      .then((response) => response.json())
      .then((json) => {
        if(list!=null && list.length>0){
          setList(old=>{
            let newList=old.slice()
            for(let i=0;i<newList.length;i++){
              newList[i].name='name:'+new Date().toString()
            }
            return newList
          })
        }
        console.log('value3:',list)
      });


  };
  useEffect(() => {
    callback.current = callBack;
    return () => {};
  });

  useEffect(() => {
    fetch('https://gw.alipayobjects.com/os/bmw-prod/1d565782-dde4-4bb6-8946-ea6a38ccf184.json')
      .then((response) => response.json())
      .then((json) => {
        setList(json)
        console.log('value0:',list)
      })
    const timer = setInterval(() => {
      callback.current();
    }, 5000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  return  <div>:{
    list&&list.map((item,index)=>{
      return <p key={index}>{item.scales}:{item.count}:{item.name} </p>
    })
  }</div>
};

export default Test;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值