【问题标题】:Not able to understand the .then (dot then ) promise in React [closed]无法理解 React 中的 .then (点 then )承诺 [关闭]
【发布时间】: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


【解决方案1】:

因为.then 的参数需要一个函数,就像onClick 一样,只是将函数传递给它,而在这种情况下为 res 的参数将被忽略。

【讨论】:

    猜你喜欢
    • 2016-01-21
    • 2023-03-15
    • 2021-10-17
    • 1970-01-01
    • 2015-01-23
    • 2017-09-04
    • 1970-01-01
    • 2020-04-27
    • 2016-11-25
    相关资源
    最近更新 更多