gpt4 book ai didi

javascript - react 条件状态更新不起作用

转载 作者:行者123 更新时间:2023-12-05 04:38:07 25 4
gpt4 key购买 nike

我正在尝试创建一个表单,用户可以在其中创建付费/免费类(class),如果付费则选择价格,但如果免费价格=0,

enter image description here

这是我的默认状态:

  const [values, setValues] = useState({
name: "",
description: "",
category: "",
price: 500,
paid: true,
uploading: false,
loading: false,
});

问题:如果我点击付费类(class),我的默认价格是 500 ,这是第一个价格价目表。但是当我更改为免费类(class)时,状态更改为“paid:false”但最后选择的价格保持如下图

enter image description here

任何想法如何改变!我尝试了几种方法,但没有任何效果。请帮忙谢谢❤️

我尝试在将它发送到后端之前更改它,但仍然没有用。

const handleSubmit = async (e) => {
e.preventDefault();
try {
if(values.paid == false) {
setValues({...values, price: 0})
}
const { data } = await axios.post("/api/course/create-new-course", {
...values,
image,
});
router.push("/instructor");
toast.success("Continue adding lessions");
} catch (err) {
console.log(err);
toast.error(err.response.data);
}
};


最佳答案

尝试像这样更新 CreateCourseForm 中的 paid 字段:

 <select
value={values.paid ? '1' : '0'}
onChange={(e) => {
const isPaid = e.target.value == '1';
setValues({ ...values, price: isPaid ? 500 : 0 , paid: isPaid })
}}
className="select select-bordered select-secondary w-full lg:w-4/5 mb-3 rounded-none lg:rounded-lg"
>
<option value={'0'}>
Free Course
</option>
<option value={'1'}>₹ Paid Course</option>
</select>

关于javascript - react 条件状态更新不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70644031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com