首页 文章

添加项目后页面不会更新

提问于
浏览
0

我是新人,刚开始学习反应 . 我遇到的问题是,当我添加一个元素时,我不会重载整个列表 . 虽然更新和删除工作正常,但更改会立即被覆盖 . 重新加载页面后,列表中会出现一个新项目 .

事实证明,当我挂载组件时,我得到一个列表并将其拉出来,当我添加一个新元素时,状态不知道它的变化 . 可能你需要立即转移到fetchNotes()给我的状态 . 如何正确创建它,请告诉我,我已经尝试使用willMount()并进行各种操作,但要么我设法填写状态,但是我不工作this.state.map( )或任何其他废话...我添加项目的方法:

class Note extends Component {
  state = {
    text: "",
    updateNoteId: null,
  };

  componentDidMount() {
    this.props.fetchNotes();
  };

 resetForm = () => {
   this.setState({text: "", updateNoteId: null});
 };

 selectForEdit = (id) => {
    let note = this.props.notes[id];
    this.setState({text: note.text, updateNoteId: id});
 };

 submitNote = (e) => {
   e.preventDefault();
   if (this.state.updateNoteId === null) {
     this.props.addNote(this.state.text).then(this.resetForm);
   } else {
     this.props.updateNote(this.state.updateNoteId, 
     this.state.text).then(this.resetForm);
   }
   this.resetForm();
};

  render() {
    return (
      <div>
        <div style={{textAlign: "right"}}>
           {this.props.user.username} (<a onClick={this.props.logout}>logout</a>)
        </div>
      <h3>Add new note</h3>
      <form onSubmit={this.submitNote}>
         <input
           value={this.state.text}
           placeholder="Enter note here..."
           onChange={(e) => this.setState({text: e.target.value})}
           required />
         <input type="submit" value="Save Note" />
      </form>
      <button onClick={this.resetForm}>Reset</button>

      <h3>Notes</h3>
      <table>
      <tbody>
        {this.props.notes.map((note, id) => (
          <tr key={`note_${id}`}>
            <td>{note.text}</td>
            <td><button onClick={() => this.selectForEdit(id)}>edit</button></td>
            <td><button onClick={() => this.props.deleteNote(id)}>delete</button></td>
          </tr>
        ))}
      </tbody>
      </table>
     </div>
     )
  }
}

const mapStateToProps = state => {
  return {
    notes: state.notes,
    user: state.auth.user,
  }
};

const mapDispatchToProps = dispatch => {
  return {
     fetchNotes: () => {
       dispatch(notes.fetchNotes());
     },
     addNote: (text) => {
        return dispatch(notes.addNote(text));
     },
     updateNote: (id, text) => {
       return dispatch(notes.updateNote(id, text));
     },
     deleteNote: (id) => {
       dispatch(notes.deleteNote(id));
     },
     logout: () => dispatch(auth.logout()),
  }
};

export default connect(mapStateToProps, mapDispatchToProps)(Note);

减速机/

const initialState = [];

export default function notes(state=initialState, action) {
  let noteList = state.slice();

  switch (action.type) {

    case 'FETCH_NOTES':
      return [...state, ...action.notes];

    case 'ADD_NOTE':
      return [...state, ...action.note];

    case 'UPDATE_NOTE':
      let noteToUpdate = noteList[action.index];
      noteToUpdate.text = action.note.text;
      noteList.splice(action.index, 1, noteToUpdate);
      return noteList;

    case 'DELETE_NOTE':
      noteList.splice(action.index, 1);
      return noteList;

    default:
      return state;
  }
}

行动

export const fetchNotes = () => {
  return (dispatch, getState) => {
    let headers = {"Content-Type": "application/json"};
    let {token} = getState().auth;

    if (token) {
      headers["Authorization"] = `Token ${token}`;
    }

    return fetch("/api/notes/", {headers, })
      .then(res => {
        if (res.status < 500) {
          return res.json().then(data => {
           return {status: res.status, data};
        })
      } else {
        console.log("Server Error!");
        throw res;
      }
    })
  .then(res => {
    if (res.status === 200) {
      return dispatch({type: 'FETCH_NOTES', notes: res.data});
    } else if (res.status === 401 || res.status === 403) {
      dispatch({type: "AUTHENTICATION_ERROR", data: res.data});
      throw res.data;
    }
  })
 }
};

export const addNote = text => {
  return (dispatch, getState) => {
    let headers = {"Content-Type": "application/json"};
    let {token} = getState().auth;

    if (token) {
      headers["Authorization"] = `Token ${token}`;
    }

    let body = JSON.stringify({text, });
      return fetch("/api/notes/", {headers, method: "POST", body})
        .then(res => {
          if (res.status < 500) {
            return res.json().then(data => {
              return {status: res.status, data};
            })
          } else {
             console.log("Server Error!");
             throw res;
          }
      })
  .then(res => {
    if (res.status === 201) {
      return dispatch({type: 'ADD_NOTE', note: res.data});
    } else if (res.status === 401 || res.status === 403) {
      dispatch({type: "AUTHENTICATION_ERROR", data: res.data});
      throw res.data;
    }
  })
  }
 };

我认为我应该以某种方式调用setState以明确指出更改,或者我可能需要在初始化组件时重新创建后端请求?

我很乐意为您提供任何提示和帮助 . 先感谢您!

1 回答

  • 1

    你应该改变reducer ADD案例如下:

    case 'ADD_NOTE':
      return {
              ...state,
              noteList:[action.note,...state.noteList]
             }
    

相关问题