繁体   English   中英

在React with Redux中从我的商店/状态中删除项目后,如何更新视图

[英]How do I get my view to update after an item was removed from my store/State in React with Redux

我是React和Redux的新手,只是对管理状态和React的想法很满意。 我开始说,因为我可能需要一种可能的解决方案,以适合我所拥有的内容,因此从本质上讲,我会更好地理解它。 :)

话虽如此,这是我的问题:

我已经在React中创建了一个列表/表单组件,但是遇到了两个明显的问题。

从数据库中删除项目时,它仅在刷新后反映在视图中。您可能已经注意到列表#或从列表中删除项目时ID列未减去。 我在后端使用PostgreSQL,并将Sequelize用作我的视图/组件的对象/关系映射器和React。

我提供了一个gif,以便大家都能理解我的意思。

提前致谢!

这是我的代码:

反应:Student.js

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(() => {
      this.setState(store.getState());
    });
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  deleteStudent(index) {
    store.dispatch(deleteStudent(index));
    this.setState(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={() => {
                              console.log(student.id);
                              this.deleteStudent(student.id);
                            }}
                            key={index}
                          >
                            <i className="fa fa-remove" />
                          </a>
                        </td>
                      </tr>
                    );
                  }, this)}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

StudentForm.js

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

const blankFormState = {
  name: "",
  email: "",
  campus: ""
};

export default class StudentForm extends Component {
  constructor(props) {
    super(props);
    this.state = blankFormState;
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const target = event.target;
    this.setState({
      [target.name]: target.value
    });
  }

  handleSubmit(event) {
    event.preventDefault();
    store.dispatch(postStudent(this.state));
    this.setState(blankFormState);
  }

  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="twelve columns">
            <form onSubmit={this.handleSubmit}>
              <div className="row">
                <div className="four columns">
                  <label>Name</label>
                  <input
                    className="u-full-width"
                    type="text"
                    name="name"
                    value={this.state.name}
                    onChange={this.handleChange}
                  />
                </div>
                <div className="four columns">
                  <label>Email</label>
                  <input
                    className="u-full-width"
                    type="text"
                    name="email"
                    value={this.state.email}
                    onChange={this.handleChange}
                  />
                </div>
                <div className="four columns">
                  <label>Campus</label>
                  <input
                    className="u-full-width"
                    type="text"
                    name="campus"
                    value={this.state.campus}
                    onChange={this.handleChange}
                  />
                </div>
              </div>
              <input className="button-primary" type="submit" />
            </form>
          </div>
        </div>
      </div>
    );
  }
}

我的reducer.js

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

const logError = console.error.bind(console);

// 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(students => {
        dispatch(getStudents(students));
      })
      .catch(logError);
  };
}

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(logError);
  };
}

export function deleteStudent(id) {
  // console.log("student", student);
  return function thunk(dispatch) {
    return axios
      .delete("/api/students" + "/" + id)
      .then(function(id) {
        return dispatch(scrubStudent(id));
      })
      .catch(function(err) {
        return console.error("Removing student: " + id + " unsuccessful", 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(logError);
  };
}

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

// 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:
      // console.log("action.student", action.student);
      // console.log("state", state);
      newState = state.students.filter(function(student) {
        return student.id !== action.id;
      });
      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;

这就是我挂载StudentsStudents StudentForm

import React, { Component } from "react";
import Students from "./Students";
import StudentForm from "./StudentForm";
import store from "../store";

import { fetchStudents } from "../reducers";

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

  componentDidMount() {
    store.dispatch(fetchStudents());
    this.unsubscribe = store.subscribe(() => this.setState(store.getState()));
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    return (
      <div>
        <Students students={this.state.students} />
        <StudentForm />
      </div>
    );
  }
}

我的store.js

import { createStore, applyMiddleware } from "redux";
import rootReducer from "./reducers";
import createLogger from "redux-logger"; // https://github.com/evgenyrodionov/redux-logger
import thunkMiddleware from "redux-thunk"; // https://github.com/gaearon/redux-thunk

export default createStore(
  rootReducer,
  applyMiddleware(thunkMiddleware, createLogger())
);

在此处输入图片说明

删除学生后,您将分派动作,并且将动作创建者scrubStudent传递给分派。 您正在该动作创建者中传递已删除学生的ID。 现在,您定义动作创建者的方式是这样的

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

因此,此函数的返回值将是这样的对象

scrubStudent(5) // returns {type: "DELETE_STUDENT", student: 5}

但是在你的减速器中,你正在像这样比较id

case DELETE_STUDENT:
      // console.log("action.student", action.student);
      // console.log("state", state);
      newState = state.students.filter(function(student) {
        return student.id !== action.id;
      });
      return newState;

在上面的代码中, action.id是未定义的。 而是将学生ID保存为action.student 因此,比较将对数组的所有元素返回true。 因此,每次所有元素都将包含在新状态中。 因此,尝试像这样更改上述代码

case DELETE_STUDENT:
      // console.log("action.student", action.student);
      // console.log("state", state);
      newState = state.students.filter(function(student) {
        return student.id !== action.student;
      });
      return newState;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM