【问题标题】:How to delete an item from a table in 'React' using 'Redux'如何使用“Redux”从“React”中的表中删除项目
【发布时间】:2017-09-01 00:18:10
【问题描述】:

此时应用程序基本上会在保存到数据库的视图中显示一个“学生”列表——现在我希望能够删除一个学生并将其保留下来。我相信答案就在组件本身。

这是我目前所拥有的——这是我的学生组件:

import React, { Component } from "react";
import store from "../store";
import { scrubStudent } from "../reducers";

export default class Students extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    this.deleteStudent = this.deleteStudent.bind(this);
  }

  deleteStudent(itemIndex) {
    console.log(this.state);
    var students = this.state.students;
    store.dispatch(scrubStudent(this.state));
    students.splice(itemIndex, 1);
    this.setState({
      students: students
    });
  }

  render() {
    var students = this.props.students;
    return (
      <div className="container">
        <div className="sixteen columns">
          <h1 className="remove-bottom">Students</h1>
          <h5>List of current students and their campus</h5>
          <hr />
        </div>
        <div className="sixteen columns">
          <div className="example">
            <div>
              <table className="u-full-width">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Campus</th>
                  </tr>
                </thead>
                <tbody>
                  {students.map(function(student, index) {
                    return (
                      <tr key={index}>
                        <td>
                          {student.id}
                        </td>
                        <td>
                          {student.name}
                        </td>
                        <td>
                          {student.email}
                        </td>
                        <td>
                          {student.campus}
                        </td>
                        <td>
                          <a
                            className="button button-icon"
                            onClick={this.deleteStudent(index)}
                          >
                            <i className="fa fa-remove" />
                          </a>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

现在我收到index.js:90 TypeError: Cannot read property 'deleteStudent' of undefined

提前致谢!

更新

根据 Matthew 的建议,我向一位老师寻求指导(我在学校),他帮助我传达了以下信息:

但现在我收到以下错误:

`index.js:90 TypeError: Cannot read property 'setState' of undefined`

我要深入研究其中的原因!

import React, { Component } from "react";
import store from "../store";
import { deleteStudent } from "../reducers";

export default class Students extends Component {
  constructor(props) {
    super(props);
    this.state = store.getState();
    this.deleteStudent = this.deleteStudent.bind(this);
  }

  componentDidMount() {
    this.unsubscribe = store.subscribe(function() {
      this.setState(store.getState());
    });
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  deleteStudent(index) {
    console.log(this.state);
    var students = this.state.students;
    store.dispatch(deleteStudent(index));
    this.state = store.getState();
  }

  render() {
    var students = this.props.students;
    return (
      <div className="container">
        <div className="sixteen columns">
          <h1 className="remove-bottom">Students</h1>
          <h5>List of current students and their campus</h5>
          <hr />
        </div>
        <div className="sixteen columns">
          <div className="example">
            <div>
              <table className="u-full-width">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Campus</th>
                  </tr>
                </thead>
                <tbody>
                  {students.map(function(student, index) {
                    return (
                      <tr key={index}>
                        <td>
                          {student.id}
                        </td>
                        <td>
                          {student.name}
                        </td>
                        <td>
                          {student.email}
                        </td>
                        <td>
                          {student.campus}
                        </td>
                        <td>
                          <a
                            className="button button-icon"
                            onClick={() => this.deleteStudent(student.id)}
                            key={index}
                          >
                            <i className="fa fa-remove" />
                          </a>
                        </td>
                      </tr>
                    );
                  }, this)}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

这是我的减速器:

import { combineReducers } from "redux";
import axios from "axios";

// INITIAL STATE

const initialState = {
  students: [],
  campuses: []
};

//ACTION CREATORS

const UPDATE_NAME = "UPDATE_NAME";
const ADD_STUDENT = "ADD_STUDENT";
const DELETE_STUDENT = "DELETE_STUDENT";
const GET_STUDENTS = "GET_STUDENTS";
const UPDATE_CAMPUS = "UPDATE_CAMPUS";
const GET_CAMPUS = "GET_CAMPUS";
const GET_CAMPUSES = "GET_CAMPUSES";

// ACTION CREATORS

export function updateName(name) {
  const action = {
    type: UPDATE_NAME,
    name
  };
  return action;
}

export function addStudent(student) {
  return {
    type: ADD_STUDENT,
    student
  };
}

export function scrubStudent(student) {
  return {
    type: DELETE_STUDENT,
    student
  };
}

export function getStudents(students) {
  const action = {
    type: GET_STUDENTS,
    students
  };
  return action;
}

export function updateCampus(campus) {
  const action = {
    type: UPDATE_CAMPUS,
    campus
  };
  return action;
}

export function getCampus(campus) {
  const action = {
    type: GET_CAMPUS,
    campus
  };
  return action;
}

export function getCampuses(campuses) {
  const action = {
    type: GET_CAMPUSES,
    campuses
  };
  return action;
}

//THUNK CREATORS

export function fetchStudents() {
  return function thunk(dispatch) {
    return axios
      .get("/api/students")
      .then(function(res) {
        return res.data;
      })
      .then(function(students) {
        return dispatch(getStudents(students));
      })
      .catch(function(err) {
        return console.error(err);
      });
  };
}

export function postStudent(student) {
  return function thunk(dispatch) {
    return axios
      .post("/api/students", student)
      .then(function(res) {
        return res.data;
      })
      .then(function(newStudent) {
        return dispatch(addStudent(newStudent));
      })
      .catch(function(err) {
        return console.error(err);
      });
  };
}

export function deleteStudent(student) {
  return function thunk(dispatch) {
    return axios
      .delete("/api/students/" + student.toString())
      .then(function(res) {
        return res.data;
      })
      .then(function(student) {
        return dispatch(scrubStudent(student));
      })
      .catch(function(err) {
        return console.error(err);
      });
  };
}

export function fetchCampuses() {
  return function thunk(dispatch) {
    return axios
      .get("/api/campuses")
      .then(function(res) {
        return res.data;
      })
      .then(function(campuses) {
        return dispatch(getCampuses(campuses));
      })
      .catch(function(err) {
        return console.error(err);
      });
  };
}

export function postCampus(student) {
  return function thunk(dispatch) {
    return axios
      .post("/api/campuses", campuse)
      .then(function(res) {
        return res.data;
      })
      .then(function(newCampus) {
        return dispatch(getCampus(newCampus));
      })
      .catch(function(err) {
        return console.error(err);
      });
  };
}

// REDUCER

const rootReducer = function(state = initialState, action) {
  var newState = Object.assign({}, state);

  switch (action.type) {
    case GET_STUDENTS:
      newState.students = state.students.concat(action.students);
      return newState;

    case ADD_STUDENT:
      newState.students = state.students.concat([action.student]);
      return newState;

    case DELETE_STUDENT:
      newState.students = state.students.concat([action.student]);
      return newState;

    case GET_CAMPUSES:
      newState.campuses = state.campuses.concat(action.campuses);
      return newState;

    case GET_CAMPUS:
      newState.campuses = state.campuses.concat([action.campus]);
      return newState;

    default:
      return state;
  }
};

export default rootReducer;

【问题讨论】:

  • 下面的答案直接回答了为什么你会收到错误但是通过阅读你的代码,你错过了 Redux 的基本点之一......**关注点分离** 在这里查看我的答案一些相关信息stackoverflow.com/questions/45936949/…
  • @MatthewBrent 确实——当我测试这个行动方案时,我达到了最大调用堆栈,一切都被破坏了!谢谢你的链接。
  • @AntonioPavicevac-Ortiz 你检查我的答案了吗?那里还有问题吗?
  • @Dekel 嘿,是的,我做到了!谢谢你。根据 Matthew 指出的内容,您可以看到我还有其他一些问题。我已经更新了我的问题以反映迄今为止的进展!
  • 在不知道上面代码中哪一行是第 90 行的情况下,这很难提供帮助,但我的猜测是,这又是一个范围问题。当您使用function() {...} 时,您会失去当前 this 的范围,这就是为什么我在回答中说您应该使用箭头功能。

标签: reactjs react-redux


【解决方案1】:

您应该使用箭头函数来将相关上下文保留在地图函数中:

{students.map((student, index) => {

这样,当您在函数内部使用 this 时 - 它就是您当前的组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    相关资源
    最近更新 更多