删除请求后组件列表未更新状态

时间:2019-04-22 16:59:07

标签: reactjs

我有一个笔记列表,每个笔记都有一个删除按钮。在显示该列表的主页组件上,删除按钮将起作用并且状态将被更新。但是,如果单击单个便笺然后将我带到单个便笺组件,则“删除”按钮将不再更新状态,但是该便笺仍将被成功删除。我必须返回主页并刷新以查看注释已从页面中删除。我正在使用上下文将属性和事件处理程序传递给一些超级嵌套的组件,包括Note组件。我不确定我缺少什么,但这是我的代码:

带有DELETE请求,状态和handleDeleteNote方法的App.js:

class App extends Component {
  state = {
    folders: [],
    notes: [],
  }
  componentDidMount() {
    this.fetchApi('folders', 'folders');
    this.fetchApi('notes', 'notes');
  }
  fetchApi(endpoint, stateKey, method = 'GET', apiBody ) {
    fetch(`http://localhost:8000/api/${endpoint}`, {
      method: method,
      headers: {
        'content-type': 'application/json'
      },
      body: JSON.stringify(apiBody)
    })
    .then(response => {
      if (method === 'DELETE') {
        return ; // if method = delete, return nothing
      } else {
        return response.json() // if method !== delete, return json response
      }
    }) 
    // ... rest of fetch call that isn't relevent to this question


  }
  handleDeleteNote(id) {
    this.fetchApi(`notes/${id.noteId}`, 'notes', 'DELETE', );
    let filtered = this.state.notes.filter(note => note.id !== id.noteId)
    this.setState({ 
      notes: filtered,
      folders: [...this.state.folders]
    });
    this.props.history.push('/');
  }

render() {
    return (
      <ErrorPage>
        <NoteContext.Provider 
          value={{
            folders: this.state.folders,
            notes: this.state.notes,
            handleDeleteNote: noteId => this.handleDeleteNote({noteId}),
          }} >
          <Route exact path="/" component={ HomePage } />
          <Route exact path="/notes/:noteId" component={ Note } />

        </NoteContext.Provider>
      </ErrorPage>
    );
  }
}

export default withRouter(App);

呈现单个注释的注释组件:

class Note extends React.Component {
  static contextType = NoteContext;

  render() {
    const { notes, handleDeleteNote } = this.context;
    const noteId = this.props.match.params.noteId;

    const filteredNotes = notes.filter(note => note.id.toString() === noteId)

    const fullNote2 = filteredNotes.map((note, index) => 
      <li key={index}>
        <h3>{note.note_name}</h3>
        <p>{note.content}</p>
        <p>Date modified: {note.modified}</p>
      </li>
      )

    return (
      <main role="main" className="App">
      <section className="main-layout">
      <div className="left-menu">
      </div>
      <div className="right-content">

        <ul className="notes-list">
            {fullNote2}
              <input 
                className="favorite styled"
                type="button"
                value="Delete note" 
                onClick={() => { handleDeleteNote(noteId)
              }}  
              /> 
        </ul>
      </div>
      </section>
      </main>
    )
  }
}

export default withRouter(Note);

0 个答案:

没有答案