【发布时间】:2021-08-03 15:32:27
【问题描述】:
我在将数据传递到 JSON 文件时遇到了一点问题。我有一个运行onClick 的函数。第一次运行返回:
{
"title": "",
"description": "",
"price": "",
"id": 1
}
但所有下一次运行都正确返回数据:
{
"title": "Example title",
"description": "Example description",
"price": "$7",
"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);
})
}
【问题讨论】: