【发布时间】:2022-10-25 01:29:22
【问题描述】:
下面是 2 个语法,第一个很清楚,关于第二种语法,我无法正常工作??
第一种语法如下:
const [products,setProducts] = useState([]);
useEffect(() => {
fetch(`${API_SERVER}/products`).then((res) => res.json()).then((res)=> setProducts([...res]);
},[]);
但无法理解下面的语法,.then(dot then)如何通过将 setProducts 函数作为参数传递给 how .then(dot then)来改变产品的状态?
const [products,setProducts] = useState([]);
useEffect(() => {
fetch(`${API_SERVER}/products`).then((res) => res.json()).then(setProducts);
},[]);
【问题讨论】:
-
在第一个示例中,您正在创建一个新函数并将其传递给
then。在第二个示例中,您只需传递已经存在的函数。then需要一个接受一个参数的函数。setProducts就是这样一个功能。 -
@KonradLinkowski 好的,很酷,现在我明白了。
标签: javascript reactjs web react-hooks es6-promise