【发布时间】:2021-12-16 14:18:43
【问题描述】:
我是 JS 的新手并做出了反应,所以到目前为止我的尝试可能还有一段路要走,而且我的代码中充满了用于调试的 console.log,但我遇到的问题是:
我有一个带有 changeHandler 和 submitHandler 函数的功能组件。 changeHandler 由“文件”输入触发,而 submitHandler 在表单提交时被调用。 submitHandler 通过 axios 对 2 个单独的端点进行 2 次调用: 1st - 在数据库中创建新记录 2nd - 将文件添加到同一条记录中。
我想将第一次调用中的 res.roundId 用作第二个 axios.post 请求中的动态变量。
我使用以下命令更新第 29 行的“详细信息”(roundId) 的状态: setDetails(prevDetails=>({ ...上一页详情, roundId:res.data.roundId }))
但是,roundId 没有更新为 res.data.roundId,因此我无法为第二次 axios 调用解构它。
关于我如何实现这一目标的任何建议? 完整代码如下:
const FileUpload = () => {
const [file, setFile]= useState(null)
const[details, setDetails] = useState({consent:false,
idConfirmed:false,
label:"",
roundId:""})
const changeHandler=(e)=>{
setFile(e.target.files[0]);
setDetails(prevDetails=>({
...prevDetails,
consent:true,
idConfirmed:true,
label:"test_Label"
}));
};
const handleSubmission=(e)=>{
e.preventDefault();
axios.post(process.env.REACT_APP_URL_NEW_ROUND, details)
.then(res=>{
console.log("Full Details: ", res)
console.log("roundId: ", res.data.roundId)
setDetails(prevDetails=>({
...prevDetails,
roundId:res.data.roundId
}))
console.log("line 31 Details: ", details)
})
console.log("roundId line 34: ", details.roundId )
//console.log("Details", details)
const data = new FormData();
data.append("file", file)
axios.post(process.env.REACT_APP_URL_All_ROUNDS/details.roundId/file/upload", data)
.then(res=>{
console.log("Data: ",res.data)
console.log("success")
})
.catch((e)=>{
console.log("Error", e)
})
};
【问题讨论】: