关于setState的一些坑

setState更新数组

你会发现,如果直接使用push等方法改变state,按理来说,push会改变原数组,数组应该更新,但渲染出来的state并不会更改

let newValue = 1;
const [array, setArray] = useState([]);
const handleChange = (newValue: number) =>{
	array.push(newValue);
	setState(array);//array更新了,但无法触发渲染
	console.log(array);//[1]
	//array增加了newValue,但渲染并未发生改变
}

render:
<p>This array is {JSON.stringify(array)}</p> //[]

这是由于js中,数组的赋值是引用传递的,array.push相当于直接更改了数组对应的内存块,但react内部用于对比的array的内存并没有更改,是指向同一个内存的,setState只做shallow compare(浅比较),因此没有触发re-render。
可以使用扩展运算符,创建一个新数组,更改内存引用

const handleChange = (newValue: number) =>{
	const newArray = [...array, newValue];
	setState(newArray);//此处本质上是改变了引用
	console.log(array);//[]
	//array并未改变,但渲染改变了
}

render:
<p>This array is {JSON.stringify(array)}</p> //[1]

或者触发展示组件的re-render,这样即使不改变数组的引用,依然可以正确显示变动。

const handleChange = (newValue: number) =>{
	setValue(newValue);
	setState(array.push(newValue));//其他更新触发了组件的re-render,此时可以正常显示变动
	console.log(array);//[1]
	//array改变,且渲染改变
}

render:
<p>This array is {JSON.stringify(array)}</p> //[1]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值