import React, { useState, useRef } from 'react';
import deepCopy from '@/utils/deepCopy';
// //深拷贝
// function deepCopy(val) {
// return JSON.parse(JSON.stringify(val));
// }
export default function demo() {
// 第一个数据就我们想要使用的组件内部数据
// 第二个数据是修改数据
// useState修改数据是异步的
let [num, setnum] = useState(0)
let [count, setcount] = useState(10)
let [list, setlist] = useState({
name: 'xx',
age: 20
})
let [arr, setarr] = useState(
[
{
name: '小米',
age: 1
},
{
name: '小满',
age: 2
},
{
name: '小红',
age: 3
}
]
)
let [goodlist, setgoodlist] = useState({})
const change1 = () => {
// 1. 这种写法会导致 视图层正常更新 ,js 逻辑层无法获取最新的值
setnum(20)
console.log('[ num ] >', num);//运行结果0 因为 setnum是异步的
// 推挤使用第二种写法 视图层正常更新 ,js 逻辑层正常更新
setcount(deepCopy(count = 100)) //必须使用深拷贝方法
console.log('[ count ] >', count);//运行结果100
list.name = 'hello'
list.age = list.age + 1
setlist(deepCopy(list))//必须使用深拷贝方法
console.log('[ list ] >', list);
arr.forEach(x => {
x.age = x.age + 1
x.gender = '男'
});
setarr(deepCopy(arr))
console.log('[ arr ] >', arr);
let arrlist = {
name: '小米',
age: 1
}
setgoodlist(deepCopy(goodlist = arrlist))
console.log('[ arrlist ] >', arrlist);
}
//普通传参
const change2 = (val) => {
console.log('[ useRef ] >', useRef)
console.log('[ val ] >', val)
}
//传递event事件对象
const change3 = (e, val) => {
console.log('[ e ] >', e)
console.log('[ val ] >', val)
}
return (
<>
<div>{list.name}{list.age}</div>
<div>{num}</div>
<div>{count}</div>
{
arr.map((item, index) =>
<div key={index}><span>{item.name}</span> <span>{item.age}</span> <span>{item.gender}</span></div>
)
}
<button onClick={change1}>按钮1</button>
<button onClick={() => change2(20)}>按钮2</button>
<button onClick={(e) => change3(e, 100)}>按钮3</button>
</>
)
}
18 react hooks 响应式数据绑定和事件绑定
于 2023-01-02 21:46:28 首次发布