在基于类的React组件中,我们可以使用setState的函数形式定义处理程序函数,如:
const handleClick =()=> {this.setState((prevState,updatedProps)=>({// return some object }))}
其中,这两个参数表示传递给该组件的先前状态和更新的道具。
类似地,我们有一个函数形式来使用useState钩子在函数组件中设置状态,如下所示:
const [count, setCount] = useState(0);
const handleClick =()=> {setCount(c=>c+1)}
但正如我们所看到的,useState钩子中的这个函数形式缺少表示更新道具的第二个参数
这是React开发团队故意留下的吗?在useState钩子中设置状态时,我们如何访问更新的道具和以前的状态?描述问题的实际代码:代码沙箱链接
通过在应用程序组件中一次导入一个,只需在两个计数器组件(一个是功能性的,另一个是基于类的(之间交替。
为什么不像这样在useEffect中触发计数(我这样修改了FunctionalCounter(,读取代码中的注释。
(这是一种非常巧妙的方式,所以只有当点击触发道具值时才会改变(
import React, { useState, useEffect } from "react";
export default function FunctionalCounter(props) {
const [count, setCount] = useState(100);
const [shouldTrigger, setShouldTrigger] = useState(false);
useEffect(() => {
if (shouldTrigger) {
setCount((c) => c + props.fromParent);
setShouldTrigger(false);
}
}, [props.fromParent,shouldTrigger]);
return (
<div>
<h3> The counter value is {count}</h3>
<button
onClick={() => {
props.handleUpdate();
setShouldTrigger(true);
}}
>
Click me
</button>
</div>
);
}
我能想到的另一种方法是返回props.handleUpdate();
上的值,这样你就可以在不依赖父级的情况下使用它,比如
App.js
const handleUpdate = () => {
const newVal = appVar + 1
setAppVar(newVal);
return newVal;
}
FunctionalCounter.js
import React, { useState } from "react";
export default function FunctionalCounter(props) {
const [count, setCount] = useState(100);
return (
<div>
<h3> The counter value is {count}</h3>
<button
onClick={() => {
const newCount = props.handleUpdate();
setCount(newCount);
}}
>
Click me
</button>
</div>
);
}