网站建设维护成,wordpress多用户小程序商城,东莞建设网站官网登录,为什么建设网站1.
useState执行后 不能立马拿到新的数据#xff0c;下次更新绘图就可以拿到了 然后当执行完第一次render时候#xff0c;比如去点击按钮啥的执行某个方法这个时候就可以拿到数据了 例子#xff1a; const UseState () { // 函数组件中没有this const [count, setCou…1.
useState执行后 不能立马拿到新的数据下次更新绘图就可以拿到了 然后当执行完第一次render时候比如去点击按钮啥的执行某个方法这个时候就可以拿到数据了 例子 const UseState () { // 函数组件中没有this const [count, setCount] useState(0)
const add () { let newCount count console.log(‘value1’, count); // 0 setCount( newCount 1) console.log(‘value2’, count); // 0 query() }
const query () { console.log(‘query函数中’, count); // 0 } return ( {count} 增加 ) } 解决方法 1可以将count的新值通过函数传参的方式传入query函数 // 改写add和query函数 const add () { let newCount count console.log(‘value1’, count); setCount( newCount 1) console.log(‘value2’, count); query(newCount) } const query (count) { console.log(‘query函数中’, count); } 2在useEffect中调用query函数因为在useEffect中组件dom已经更新完毕可以拿到count的最新值缺点每次count值改变都会触发useEffect从而执行query函数 // 组件每次渲染之后执行的操作执行该操作时dom都已经更新完毕 useEffect((){ // 1、可在此处拿到count更新后的值 console.log(‘value3’, count); query() }, [count])
const add () { let newCount count console.log(‘value1’, count); setCount( newCount 1) console.log(‘value2’, count); } const query () { console.log(‘query函数中’, count); } 3通过useRef()定义一个可变的ref变量通过current属性保存count可变值从而在count更新后通过ref的current属性拿到更新后的count值注意调用query函数时需要加上setTimeout()进行调用
// 定义一个可变的countRef对象该对象的current属性被初始化为传入的参数count; const countRef useRef(count)
// 在countRef.current属性中保存一个可变值count的盒子 countRef.current count
const add () { let newCount count console.log(‘value1’, count); setCount( newCount 1) console.log(‘value2’, count); setTimeout(() query(), 0); }
const query () { console.log(‘query函数中’, countRef.current); }
2.
下次更新绘图就可以拿到了 然后当执行完第一次render时候比如去点击按钮啥的执行某个方法这个时候就可以拿到新的数据了 例子 const [init, setInit] useState() const inti async () { setInit(true) }; useEffect(() { init(); }, []); const fn async () { console.log(881, init); };