reactjs 从数组react js中删除项目

lmvvr0a8  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(130)

我在使用removing an object from an array时遇到了问题。我尝试了许多选项,但没有任何效果。请帮助我解决此问题。
谢谢你的帮忙
我的数组:

export const SavedList = [
    {
      word: 'hello',
      translate: 'привет',
      note: 'say say'
    }
]

删除回调(deletePost)

class Menu extends Component {
  state = { 
    word: '',
    translate: '',
    note: '',
    data: SavedList,
  }
  deletePost =(id)=>{
    this.setState({
      data : this.state.data.filter((el)=> el.id !== id)
    })
  }
  render() {
    return (
          <div className="content">
            <Routes>
              <Route path="/" element={<Layout />}>
                  <Route path="saved" element={<Saved data={this.state.data} del={this.deletePost}/>}/>
              </Route>
            </Routes>
            <div>
            </div>
        </div>
    );
  }
}
export default Menu;

此处按钮deleteonClick

class Saved extends Component {
  render() {
    const sl = this.props.data.map((sl, id) => {
      return (
        <div className="saved-card" key={id}>
          <div className="content">
            <p>{id}</p>
            <p>{sl.word}</p>
            <p>{sl.translate}</p>
            <p>{sl.note}</p>
          </div>
          <div className="btn-block">
            <button
              onClick={() => this.props.del(id)}
              type="button"
              className="delete-btn"
            >
              delete
            </button>
          </div>
        </div>
      );
    });
    return (
      <div>
        <h2>Saved list</h2>
        <div className="saved-inner">
          <div className="saved-list">{sl}</div>
        </div>
      </div>
    );
  }
}

export default Saved;
eivgtgni

eivgtgni1#

这个问题是因为el.id在delete Post函数中没有任何值。该函数还需要一个ID变量,我将其命名为i_di。

class App extends Component {
  state = { 
    word: '',
    translate: '',
    note: '',
    data: SavedList,
  }
  deletePost =(id)=>{
    this.setState({
      data : this.state.data.filter((el, i_di)=> i_di !== id )
    })
  }
  render() {
    return (
          <div className="content">
              {<Saved data={this.state.data} del={this.deletePost}/>}
            
        </div>
    );
  }
}
export default App;

相关问题