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;