Javascript 在 ReactJS 中删除项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35901920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deleting an item in ReactJS
提问by Virge Assault
I'm new to React and made an app that allows searches to be saved. This will pull JSON but is currently pulling from a static array data
. I'm having trouble being able to delete searches from the search list.
我是 React 的新手,并制作了一个允许保存搜索的应用程序。这将拉取 JSON,但目前正在从静态数组中拉取data
。我无法从搜索列表中删除搜索。
Here's the jsbin: http://jsbin.com/nobiqi/edit?js,output
这是jsbin:http://jsbin.com/nobiqi/edit?js,output
Here's my delete button element:
这是我的删除按钮元素:
var DeleteSearch = React.createClass({
render: function() {
return (
<button onClick="this.props.deleteSearchItem" value={index}><i className="fa fa-times"></i>
</button>
);
}
});
and my function
和我的功能
deleteSearchItem: function(e) {
var searchItemIndex = parseInt(e.target.value, 10);
console.log('remove task: %d', searchItemIndex);
this.setState(state => {
state.data.splice(searchItemIndex, 1);
return { data: state.data };
});
}
I've tried following tutorials and I'm not sure where to go from here. How can I delete the search items?
我试过遵循教程,但我不知道从哪里开始。如何删除搜索项?
回答by The Reason
Let me guess, Are you looking for something like this?
让我猜猜,你在寻找这样的东西吗?
class Example extends React.Component {
constructor(){
this.state = {
data: [
{id:1, name: 'Hello'},
{id:2, name: 'World'},
{id:3, name: 'How'},
{id:4, name: 'Are'},
{id:5, name: 'You'},
{id:6, name: '?'}
]
}
}
// shorter & readable
delete(item){
const data = this.state.data.filter(i => i.id !== item.id)
this.setState({data})
}
// or this way, it works as well
//delete(item){
// const newState = this.state.data.slice();
// if (newState.indexOf(item) > -1) {
// newState.splice(newState.indexOf(item), 1);
// this.setState({data: newState})
// }
//}
render(){
const listItem = this.state.data.map((item)=>{
return <div key={item.id}>
<span>{item.name}</span> <button onClick={this.delete.bind(this, item)}>Delete</button>
</div>
})
return <div>
{listItem}
</div>
}
}
React.render(<Example />, document.getElementById('container'));
In this example pay attention how i'm binding delete
method and pass there new parameter. fiddle
在此示例中,请注意我如何绑定delete
方法并传递新参数。小提琴
I hope it will help you.
我希望它会帮助你。
Thanks
谢谢
回答by Virge Assault
OP here. Since I know more about React four years later and this still gets views I figured I'd update this with how I'd go about it now.
在这里。因为四年后我对 React 有了更多的了解,而且这仍然引起人们的关注,所以我想我会用我现在的做法来更新它。
SavedSearches.js
SavedSearches.js
import React from 'react'
import { SearchList } from './SearchList'
let data = [
{index: 0, name: "a string", url: 'test.com/?search=string'},
{index: 1, name: "a name", url: 'test.com/?search=name'},
{index: 2, name: "return all", url: 'test.com/?search=all'}
];
let startingIndex = data.length;
export class SavedSearches extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
url: '',
index: startingIndex,
data: data
}
this.deleteSearch=this.deleteSearch.bind(this)
}
deleteSearch(deleteThis) {
console.log(deleteThis);
let newData = this.state.data.filter( searchItem => searchItem.index !== deleteThis.index )
this.setState({
data: newData
})
}
render() {
return (
<div className="search-container">
<SearchList data={this.state.data} onDelete={this.deleteSearch}/>
</div>
)
}
}
Here I created a method called deleteSearch
that takes an object as a parameter. It then runs .filter
on the this.state.data
array to create a new array that includes all items that don't meet the condition. The condition checks if the id of each object in the data array matches the id of the parameter. If so, then it is the one that is being deleted. The new array that is created by .filter
is set to a variable called newData
, and then I update the state with the newData
array.
在这里,我创建了一个名为的方法deleteSearch
,该方法将对象作为参数。然后它.filter
在this.state.data
数组上运行以创建一个包含所有不满足条件的项目的新数组。条件检查数据数组中每个对象的 id 是否与参数的 id 匹配。如果是这样,那么它就是被删除的那个。创建的新数组.filter
被设置为一个名为 的变量newData
,然后我用该newData
数组更新状态。
I then pass this method to the SearchList
component in a prop called onDelete
.
然后我将此方法传递给SearchList
名为onDelete
.
This method is also bound in the constructor using .bind()
so that this
will refer to the correct this
when the method is passed down the component tree.
此方法也绑定在构造函数 using 中,.bind()
以便在该方法沿组件树向下传递时this
将引用正确this
的方法。
SearchList.js
搜索列表.js
import React from 'react'
import { SearchItem } from './SearchItem'
export class SearchList extends React.Component {
render() {
let searchItems = this.props.data.map((item, i) => {
return (
<SearchItem index={i} searchItem={item} url={item.url} onDelete={this.props.onDelete}>
{item.name}
</SearchItem>
);
});
return (
<ul>
{searchItems}
</ul>
);
}
}
My deleteSearch
method is just passing through the component tree here. SearchList
receives the method as a props this.props.onDelete
and passes it to SearchItem
.
我的deleteSearch
方法只是通过这里的组件树。SearchList
接收该方法作为道具this.props.onDelete
并将其传递给SearchItem
.
The other major key here is that the parameter in the map function is being passed as props: searchItem={item}
. This will allow the entire current object to be accessed via props; and if you remember, my deleteSearch
function takes an object as a parameter.
这里的另一个主要关键是 map 函数中的参数作为 props: 传递searchItem={item}
。这将允许通过 props 访问整个当前对象;如果你还记得的话,我的deleteSearch
函数接受一个对象作为参数。
SearchItem.js
搜索项.js
import React from 'react'
export class SearchItem extends React.Component {
constructor(props) {
super(props);
this.handleDelete=this.handleDelete.bind(this)
}
handleDelete() {
this.props.onDelete(this.props.searchItem)
}
render() {
return (
<li key={this.props.index}> {/* Still getting a console error over this key */}
<a href={this.props.url} title={this.props.name}>
{this.props.children}
</a>
({this.props.url})
<button onClick={this.handleDelete} value={this.props.index}><i className="fa fa-times"></i>
</button>
</li>
);
}
};
Now my method arrives where it will be used. I create a handler method handleDelete
and inside I access the deleteSearch
method with this.props.onDelete
. I then pass it the object of the list item that is being clicked on with this.props.searchItem
.
现在我的方法到达了它将被使用的地方。我创建了一个处理程序方法,handleDelete
并在内部deleteSearch
使用this.props.onDelete
. 然后我将正在单击的列表项的对象传递给它this.props.searchItem
。
In order for this to work when a user clicks, I had to add an onClick
event listener that calls my handler method, like this: onClick={this.handleDelete}
. The final step is to bind this.handleDelete
in the SearchItem
constructor method.
为了这个工作,当用户点击,我不得不添加一个onClick
事件侦听器调用我的处理方法,就像这样:onClick={this.handleDelete}
。最后一步是this.handleDelete
在SearchItem
构造函数方法中绑定。
Now, clicking on the button will remove the item from the this.state.data
array. For an example of how to add an item to the array, see my repository
现在,单击该按钮将从this.state.data
数组中删除该项目。有关如何向数组添加项目的示例,请参阅我的存储库