useState状态变量未更新



所以我使用useState方法创建了一些状态变量:

const [claim1,setclaim1]=useState("Pending");
const [claim2,setclaim2]=useState("Pending");
const [claim3,setclaim3]=useState("Denied");
const [claim4,setclaim4]=useState("Pending");

然后,我在呈现方法中插入这些变量,以显示每个声明的状态。我的问题是,当我尝试更新它们时,我使用了一个具有onclick功能的按钮,该按钮将setclaim1使用到适当的状态。按钮看起来像这个

<button onclick={()=> setclaim1('Approved')} type="approve" className="submitbutton" >

我也尝试在onclick之后使用useEffect,但这最终会在页面渲染后更新变量,即使我没有单击按钮。任何指向正确方向的指针都将是伟大的

完整代码:

// JavaScript source code
import { useNavigate } from "react-router-dom";
import logo from './assets/logo.png';
import React, {useState} from'react';

const ClaimApproval = () => {
let navigate = useNavigate();
const onclick = () => {
navigate("/mainpageLM")
}
const [claim1,setclaim1]=useState("Pending");
const [claim2,setclaim2]=useState("Pending");
const [claim3,setclaim3]=useState("Denied");
const [claim4,setclaim4]=useState("Pending");



return (
<>
<div className="formpage">
<a onClick={onclick}><img className="logoForm" src={logo}></img></a>
<h1 className='form-title'>Manager Approval</h1>
<form className="form" class='center' align='middle'>
<fieldset text-align='center'>
<table class='center'>
<tr>
<th>Name</th>
<th>Amount</th>
<th>Status</th>
<th>File</th>
<th>Approve/Deny</th>
</tr>
<tr>
<th>Amy Darwin</th>
<th>$12.75</th>
<th>{claim1}</th>
<th>Claim.pdf</th>
<th><button onclick={()=> setclaim1('Approved')} type="approve" className="submitbutton" >Approve</button> <button type="approve" className="submitbutton" >Deny</button></th>
</tr>
<tr>
<th>James Peters</th>
<th>$34.34</th>
<th>{claim2}</th>
<th>expense_claim.pdf</th>
<th><button type="approve" className="submitbutton" >Approve</button> <button type="approve" className="submitbutton" >Deny</button></th>
</tr>
<tr>
<th>Arch Mathis</th>
<th>$45.32</th>
<th>{claim3}</th>
<th>claim12.pdf</th>
<th><button type="approve" className="submitbutton" >Approve</button> <button type="approve" className="submitbutton" >Deny</button></th>
</tr>
<tr>
<th>Mark Collins</th>
<th>$23.45</th>
<th>{claim4}</th>
<th>claim.pdf</th>
<th><button type="approve" className="submitbutton" >Approve</button> <button type="approve" className="submitbutton" >Deny</button></th>
</tr>
</table>
</fieldset>

</form>
</div>
</>
)
}
export default ClaimApproval;

在React中使用onClick而不是像那样使用onClick

<button onClick={()=> setclaim1('Approved')} className="submitbutton" >

也要使用className而不是class。

这是单据

看起来您有一个拼写错误:按钮的道具不是"onclick",而是"Click">

对于未来,我建议你看看你的控制台,你可能会清楚地看到这种错误。

最新更新