函数首先传递 null 运行

Function passing null at first run

我在将数据传递到 JSON 文件时遇到了一点问题。我有一个 运行s onClick 的函数。第一个运行返回:

{
   "title": "",
   "description": "",
   "price": "",
   "id": 1
}

但所有接下来的 运行s returns 数据正确:

{
   "title": "Example title",
   "description": "Example description",
   "price": "",
   "id": 2
}

有人知道怎么解决吗?

我的反应代码:

    const [title, setTitle] = useState('');
    const [description, setDescription] = useState('');
    const [price, setPrice] = useState('');

    const addToCart = (e) => {
        e.preventDefault();
        setTitle('Example title');
        setDescription('Example description');
        setPrice('$' + Math.floor(Math.random() * 10 + 1));

        const product = { title, description, price};

        fetch('http://localhost:8000/basket', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(product)
        })
        .catch((err) => {
            console.log(err.message);
        })
    }

它可能会中断,因为您在进行提取调用时试图在初始空状态值上设置状态。这里的设计是错误的,您不应该在进行提取调用时分配硬编码状态。

const Form = () => {
  const [value, setValue] = useState('')

  const submit = () => {
    // make fetch call here using value
  }

  return <form onSubmit={(e) => {e.preventDefault(); submit()}}>
    <input type='text' value={value} onChange={(e) => setValue(e.target.value)}
  </form>
}

因为 setState 是异步的,只有在组件重新渲染时才会更新。因此,您可以声明要在 post 和 setState.

中使用的变量
const addToCart = (e) => {
  e.preventDefault();

  const product = {
    title: "Example title",
    description: "Example description",
    price: "$" + Math.floor(Math.random() * 10 + 1),
  };

  setTitle(product.title);
  setDescription(product.description);
  setPrice(product.price);

  fetch("http://localhost:8000/basket", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(product),
  }).catch((err) => {
    console.log(err.message);
  });
};