我似乎把一切都传递正确了。
- 当我尝试从我的数组中删除项目时,它会删除除我想要删除的项目外的所有其他项目。也祭坛项目。例如,如果条目是字符串ss.
- 如果我从数组中删除2个字符的最后一项,例如77。它会将数组中每个长度为2个字符的项更改为7个字符。并删除所有其他项
- 如果我从数组中删除第一项它会清除整个数组
what I need to happen
从数组中删除与var itemIndex匹配的项
父comp
const Pagethree = () => {
const[items,setItem] = useState([]);
return(
<ul>
{
items.map((items, i) =>
<ListItem index={i} item={items} setItem={setItem}/>)
}
</ul>
)
孩子comp
import React, {useState} from "react";
const ListItem = (props) =>{
const {item, setItem, index} = props;
const removeItem = e =>{
var array = [...item];
var indexItem = index;
if (indexItem !== -1){
array.splice(indexItem, 1);
setItem(array);
}
console.log(array);
}
return(
<div>
<ul>
{
<div class="flex">
{item}
<button onClick={removeItem}>delete</button>
</div>
}
</ul>
</div>
)
};
export default ListItem;
父组件应该管理状态。所有你应该从父组件传递给子组件的是它需要呈现的数据,以及删除按钮的处理程序。
const { useState } = React;
// Passing a value, and index, and the handler
function ListItem({ value, index, updateState }) {
// When `handleDelete` is called, call
// the `updateState` with the item index
// as an argument
function handleDelete() {
updateState(index);
}
// The button calls the local function when
// it is clicked
return (
<li>
{value}
<button onClick={handleDelete}>Delete</button>
</li>
);
}
function Example({ data }) {
const [ items, setItems ] = useState(data);
// `filter` out the items that don't have
// the deleted item's index, and update state
function updateState(index) {
const updated = items.filter((_, i) => i !== index);
setItems(updated);
}
// `map` over the data making sure
// that `updateState` is passed down in the props
return (
<ul>
{items.map((el, i) => {
return (
<ListItem
key={i}
value={el}
index={i}
updateState={updateState}
/>
)
})}
</ul>
);
};
const data = [1, 2, 3, 4 ];
ReactDOM.render(
<Example data={data} />,
document.getElementById('react')
);
ul { list-style-type: none; padding: 0; margin: 0; }
li { margin-bottom: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>