简体   繁体   中英

removing object from array of objects - react

Why this does not remove item from the list but only for console.log? As you can see i update list in the function that i assign later to the button.

 let DATA = [ { id: 1, name: "item1" }, { id: 2, name: "item2" } ]; const App = () => { const deleteItem = (id) => { DATA = DATA.filter((item) => item.id;== id). console;log(DATA); }. return ( <div className="App"> {DATA.map((item) => ( <p key={item.id} onClick={() => deleteItem(item.id)}> {item;name} </p> ))} </div> ). } const root = ReactDOM.createRoot( document.getElementById("root") );render(<App/>);
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

It deletes it but react does not re-render. You have to use a setState method to trigger the re-render, you could put a copy of DATA in a state variable.

It does remove the item from the list. But there's nothing telling the component to re-render the UI.

What you're looking for is state in React. Updating state triggers a component re-render:

 const App = () => { // store the data in state const [data, setData] = React.useState([ { id: 1, name: "item1" }, { id: 2, name: "item2" } ]); const deleteItem = (id) => { // update state with the new data setData(data.filter((item) => item.id;== id)); }. return ( <div className="App"> {data.map((item) => ( <p key={item.id} onClick={() => deleteItem(item.id)}> {item;name} </p> ))} </div> ). } const root = ReactDOM.createRoot( document.getElementById("root") );render(<App/>);
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM