【发布时间】:2021-11-30 00:57:55
【问题描述】:
我正在获取默认输入字段值(从 API 获取数据),然后更新其中一些,然后再次通过 API 将数据发布到后端。 但是当我再次将数据发送到后端时,只会出现那些由我更新的值。其余值显示为 null,因为它们没有采用默认值。
这是我的代码:
export default function ReferralPayment() {
const [data, setData] = useState({});
const [member,setMember]=useState({ RefPerLVL1:"",RefPerLVL2:"",RefPerLVL3:"",RefPerLVL4:"",RefPerLVL5:"",RefPerLVL6:"",RefPerLVL7:"",RefPerLVL8:"",RefPerLVL9:"",RefPerLVL10:"",RefPerLVL11:"",RefPerLVL12:""
})
var name,value;
const handleInputs=e=>{
name=e.target.name;
value=e.target.value;
setMember({...member,[name]:value})
}
const postData=async (e)=>{
const {RefPerLVL1,RefPerLVL2,RefPerLVL3,RefPerLVL4,RefPerLVL5,RefPerLVL6,RefPerLVL7,RefPerLVL8,RefPerLVL9,RefPerLVL10,RefPerLVL11,RefPerLVL12}=member;
const res=await fetch("/refpaypost",{
method:"POST",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
RefPerLVL1,RefPerLVL2,RefPerLVL3,RefPerLVL4,RefPerLVL5,RefPerLVL6,RefPerLVL7,RefPerLVL8,RefPerLVL9,RefPerLVL10,RefPerLVL11,RefPerLVL12
})
});
const data=await res.json();
}
useEffect(() => {
async function fetchBooks() {
const response = await fetch('/refpayget');
const json = await response.json();
setData(json.rf2);
console.log(json.rf2)
}
fetchBooks();
},[]);
if (!data.length) {
return null;
}
return (
<table style={{width:"80%",marginLeft:"20%"}}>
<h4 style={{color:'black'}}>Referance Payments</h4>
{ data.map((val,index)=>
<tbody>
<tr>
<td>LVL1</td>
<td>{val. RefPerLVL1}%</td>
<td> <Button variant="light" onClick={()=>{setShow(true);settext("LVL1 Payment Percentage");setname("RefPerLVL1")}}><Pencil size={20}/></Button></td>
</tr>
<tr>
<td>LVL2</td>
<td>{val.RefPerLVL2}%</td>
<td> <Button variant="light" onClick={()=>{setShow(true);settext("LVL2 Payment Percentage");setname("RefPerLVL2")}}><Pencil size={20}/></Button></td>
</tr>
</tbody>
)}
</table>
<Form >
<Row >
<Col ><Form.Text className="text-muted">LVL1 Payment Percentage</Form.Text></Col>
<Col><Form.Control size="sm" type="text" name="RefPerLVL1" placeholder="Enter Amount" autoFocus defaultValue={data[0].RefPerLVL1} onChange={e=>handleInputs(e)}/></Col>
</Row>
<Row >
<Col ><Form.Text className="text-muted">LVL2 Payment Percentage</Form.Text></Col>
<Col><Form.Control size="sm" type="text" name="RefPerLVL2" placeholder="Enter Amount" defaultValue={data[0].RefPerLVL2} onChange={e=>handleInputs(e)}/></Col>
</Row>
<Row >
<Col ><Form.Text className="text-muted">LVL3 Payment Percentage</Form.Text></Col>
<Col><Form.Control size="sm" type="text" name="RefPerLVL3" placeholder="Enter Amount" defaultValue={data[0].RefPerLVL3} onChange={e=>handleInputs(e)}/></Col>
</Row>
</Form>
<Button variant="dark" onClick={()=>postData()}>
Save Changes
</Button>
如果我没有单击输入字段,它不会更改并且值似乎为空,因为 member usestate 默认具有空值。
那么,当我没有更改输入字段时,如何只使用输入字段的默认值呢?
如果我尝试用data usestate 初始化member usestate,我该怎么做?
【问题讨论】: