【发布时间】:2023-02-01 03:46:09
【问题描述】:
我正在关注 tutorial 如何结合使用 React 和 Java(使用 Ionic 和 Typescript),但我对 JavaScript 了解不多。这是一个简单的 CRUD,您可以在其中添加、编辑和删除列表的客户端。很简单,但是当我创建一个新客户端时,它既编辑(或创建)了一个对象,又复制了它的条目。我想问题出在“保存”按钮上,但我找不到问题所在。
这是创建和编辑对象的具体编辑Client.tsx
const { name, id } = useParams<{
name: string;
id: string;
}>();
const [client, setClient] = useState<any>({});/* this array will be called when we do a search*/
useEffect(() => {search();}, []);
const history = useHistory();
const search = () => {
if(id !== 'new') {
let result = searchClientById(id);
setClient(result);
}
}
const save = () => {
saveClient(client);
history.push('/page/clients')
}
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonButtons slot="start">
<IonMenuButton />
</IonButtons>
<IonTitle>{name}</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent fullscreen>
<IonHeader collapse="condense">
<IonToolbar>
<IonTitle size="large"></IonTitle>
</IonToolbar>
</IonHeader>
<IonCard>
<IonTitle>{id === 'new' ? 'Set New Client' : 'Edit Client'}</IonTitle>
<IonRow>
<IonCol>
<IonItem>
<IonLabel position="stacked">Name</IonLabel>
<IonInput onIonChange={e => client.firstname = e.detail.value} value={client.firstname}></IonInput>
</IonItem>
</IonCol>
<IonCol>
<IonItem>
<IonLabel position="stacked">Surname</IonLabel>
<IonInput onIonChange={e => client.surname = e.detail.value} value={client.surname}></IonInput>
</IonItem>
</IonCol>
</IonRow>
<IonRow>
<IonCol>
<IonItem>
<IonLabel position="stacked">Email</IonLabel>
<IonInput onIonChange={e => client.email = e.detail.value} value={client.email}></IonInput>
</IonItem>
</IonCol>
<IonCol>
<IonItem>
<IonLabel position="stacked">Adress</IonLabel>
<IonInput onIonChange={e => client.address = e.detail.value} value={client.address}></IonInput>
</IonItem>
</IonCol>
<IonCol>
<IonItem>
<IonLabel position="stacked">Phone</IonLabel>
<IonInput onIonChange={e => client.phone = e.detail.value} value={client.phone}></IonInput>
</IonItem>
</IonCol>
</IonRow>
<IonItem>
<IonButton onClick={save} color="primary" fill='solid' slot='end' size='default'>
<IonIcon icon={checkmark} />
Save Changes
</IonButton>
</IonItem>
</IonCard>
</IonContent>
</IonPage>
);
这是在前面的代码中调用的 clientApi.tsx 中特定的 saveClient 函数
export function saveClient(client:any) {
let clients = searchClient(); //array with clients
if(client.id) {
//edit - search by id & replace
let index = clients.findIndex((c:any) => c.id == client.id);
clients[index] = client;
}else {
//new - generates id & does a push to the array
client.id = Math.round(Math.random()*10000);
clients.push(client);
}
clients.push(client); //in that array we add the client we recive [].push(client)
localStorage['clients'] = JSON.stringify(clients); //we transform it into a string
}
我在 editClient.tsx 的保存功能中尝试了一个调试器,但无法让它向我展示对象是如何加载的。我根据教程对其进行了审查,并排除了它所针对的语言差异。我认为这可能是一个错字。
【问题讨论】:
标签: javascript node.js reactjs ionic-framework