【问题标题】:How to make async/await function till state update in MERN Stack Application如何在 MERN 堆栈应用程序中进行异步/等待功能直到状态更新
【发布时间】:2021-08-27 14:22:41
【问题描述】:

我想让我的函数等待chosenImage 状态更新。我可以在addToCart 函数中看到console.log 中的更新状态,但是里面的console.log 返回空字符串。我怎样才能让它等待状态更新?

这就是我的意思:

const [chosenImage, setChosenImage] = useState('');
    
console.log(chosenImage)
    
const addToCart = (user, product) => {

  console.log(chosenImage)

  const cartProduct = {
    _id: product._id,
    name: product.name,
    description: product.description,
    processor: product.processor,
    ram: product.ram,
    storage: product.storage,
    price: product.price,
    type: product.type,
    likes: product.likes,
    colors: product.colors,
    images: chosenImage
  }

  fetch(`${API}/cart/usercart`, {
    method:"POST",
    headers: { 
      'Content-Type': 'application/json'
    },
    body: JSON.stringify([user._id, cartProduct])
  })
  .then(response => response.json())
  .then(response => {
    const updatedCart = response.cart;
    setUser(oldState => ({...oldState, cart: [updatedCart]}))
    localStorage.setItem("cart", JSON.stringify(updatedCart))
  })
  .catch(error => console.log(error))
}

【问题讨论】:

  • 我没有看到你打电话给setChosenImage。或者您想致电addToCard 何时 chosenImage 更新?
  • 是的,当 selectedImage 更新时调用 addToCard

标签: reactjs


【解决方案1】:

您需要使用useEffect 来收听该属性的更新。来自the docs:

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

基本上你会在useEffect 处理程序中调用你的addToCard 方法。更多信息在这里:How can React useEffect watch and update state?

【讨论】:

  • 这个函数addToCart 在另一个文件中,我从Products 页面更新它。我的意思是更新状态的功能和按钮在不同的文件中
【解决方案2】:

为了等待状态更新然后执行then函数,你需要使用useEffect将状态作为依赖

...
useEffect(()=>{
   addToCart(user, product)
},[chosenImage])

【讨论】:

  • 好的,但似乎我无法使用 addToCart(user, product) 实现该功能,它不接受周围的 { } 。
  • 什么意思?您在 useEffect 之外简单地创建函数addToCart,在钩子内部,您只需调用它并传入参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-10
  • 2020-02-01
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
相关资源
最近更新 更多