![](/img/trans.png)
[英]How to remove an item from array if it's been clicked (and if it already has been previously added to an array)?
[英]Why array has been lost last item?
這是我的代碼
import React, {useState} from 'react'; const TestForm = props => { const [emailInput, setEmailInput] = useState([]); const removeEmail = useCallback( (e, id) => { console.log(emailInput); }); const addEmail = () => { const timestamp = (new Date()).getTime(); setEmailInput([...emailInput, <EmailInvitation key={timestamp} removeEmail={(e) => removeEmail(e, timestamp)} />] ); }; return ( <div> <div> <input name="email[]" type="email" placeholder="Enter Email" /> </div> {emailInput ? emailInput.map( eI => eI) : null} <button type="button" onClick={addEmail} /> </div> ); } const EmailInvitation = props => { const { removeEmail } = props; return ( <div> <input name="email[]" type="email" placeholder="Enter Email" /> <button type="button" onClick={removeEmail}> Remove </button> </div> ); };
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
當我單擊具有 removeEmail 功能的按鈕時,我得到console.log(emailInput);
但是這個數組丟失了最后一項。
示例:單擊addEmail
兩次后我有 3 個輸入。 當我點擊第一個刪除按鈕時,我得到了任何東西。 單擊第二個刪除按鈕,我只得到了數組中的第一個項目,錯過了當前項目。 單擊第三個刪除按鈕,它只顯示 2 個項目(第一和第二)
在codesandbox.io上的這段代碼: https ://codesandbox.io/s/condescending-oskar-jqbxz
我還沒有深入挖掘到哪里/為什么,但我的預感以某種方式將狀態記錄到回調中似乎得到了證實。 當我更新您的沙箱以僅存儲時間戳和狀態並在渲染周期中完全渲染EmailInvitation
,它似乎按照我認為您的意圖/預期運行。
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
const TestForm = props => {
const [timesStamps, setTimestamps] = useState([]);
const removeEmail = (e, id) => {
console.log(timesStamps, id); // full timestamps array and timestamp/id invoking callback
};
const addEmail = () => {
const timestamp = new Date().getTime();
setTimestamps([...timesStamps, timestamp]);
};
useEffect(() => console.log("timesStamps", timesStamps), [timesStamps]);
return (
<div>
<div>
<input name="email[]" type="email" placeholder="Enter Email" />
</div>
{timesStamps.map(timestamp => (
<EmailInvitation
key={timestamp}
timestamp={timestamp}
removeEmail={removeEmail} // link callback ref here
/>
))}
<button type="button" onClick={addEmail}>
Add
</button>
</div>
);
};
const EmailInvitation = ({ timestamp, removeEmail }) => {
return (
<div>
<input name="email[]" type="email" placeholder="Enter Email" />
<button
type="button"
onClick={e => removeEmail(e, timestamp)} // invoke with event
>
Remove
</button>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<TestForm />, rootElement);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.