javascript - react 错误 : NotFoundError: Failed to execute 'removeChild' on 'Node' : The node to be removed is not a child of this node

标签 javascript reactjs

我是新来的 react 。当我搜索 React 应用程序时,我得到了如上所示的错误。我的组件是,

用户列表

import React, { Component } from "react";
import $ from "jquery";
import UserStore from "../../stores/UserStore";
import * as UserActions from "../../actions/UserActions";
import AddUser from "./AddUser";
import moment from "moment";
import Search from "../Search";

$.DataTable = require("datatables.net");

class UserList extends Component {
  constructor() {
    super();
    this.getUsers = this.getUsers.bind(this);
    this.state = {
      users: UserStore.getAll()
    };
    // this.loadUsers();
  }

  componentDidMount() {
    $(document).ready(function() {
      $("#example").DataTable({
        ordering: true
      });
    });
  }

  componentWillMount() {
    UserStore.on("change", this.getUsers);
  }

  componentWillUnmount() {
    UserStore.removeListener("change", this.getUsers);
  }

  getUsers() {
    console.log(" get users called");
    this.setState({
      users: UserStore.getAll()
    });
  }

  loadUsers() {
    UserActions.getUsersList();
  }

  render() {
    console.log("users " + JSON.stringify(this.state.users));
    const userlistitem = this.state.users.map((user, index) => (
      <tr key={index}>
        <td scope="row">{index}</td>
        <td>{user.name}</td>
        <td>{user.username}</td>
        <td>{user.email}</td>
        <td>{moment(user.dob).format("DD-MM-YYYY")}</td>
        <td>{user.address}</td>
        <td>{user.mobile}</td>
        <td>{user.branch}</td>
      </tr>
    ));
    return (
      <div>
        <Search />

        <div
          style={{
            marginTop: 80,
            marginLeft: 150,
            marginRight: 150
          }}
        >
          <div className="card text-white bg-info mb-3">
            <div className="card-body">
              <div className="d-flex justify-content-between">
                <h5>User List</h5>
                <div>
                  <button
                    style={{
                      marginTop: 10
                    }}
                    type="button"
                    className="btn btn-light "
                    data-toggle="modal"
                    data-target="#exampleModalCenter"
                  >
                    Add New User
                  </button>
                </div>
              </div>
            </div>
          </div>

          <table id="example" className="table table-bordered  table-striped ">
            <thead className="thead-dark">
              <tr>
                <th scope="col">#</th>
                <th scope="col">Name</th>
                <th scope="col">User Name</th>
                <th scope="col">Email</th>
                <th scope="col">DOB</th>
                <th scope="col">Address</th>
                <th scope="col">Mobile</th>
                <th scope="col">Branch</th>
              </tr>
            </thead>
            <tbody>{userlistitem}</tbody>
          </table>
          <AddUser />
        </div>
      </div>
    );
  }
}

export default UserList;

搜索

import React, { Component } from "react";
import * as UserActions from "../actions/UserActions";
import "../css/search.css";

import ToggleDisplay from "react-toggle-display";
import UserList from "./User/UserList";

class Search extends Component {
  constructor(props) {
    super(props);

    this.state = {
      name: "",
      username: "",
      mobile: "",
      usercreateddate: "",
      show: false
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.searchquery = this.searchquery.bind(this);
  }

  handleInputChange(e) {
    const target = e.target;
    const value = target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  searchquery = () => {
    const search = {
      name: this.state.name,
      username: this.state.username,
      mobile: this.state.mobile,
      usercreateddate: this.state.usercreateddate
    };
    console.log("sdsdsd" + JSON.stringify(search));
    UserActions.searchEvents(search);
    this.setState({
      show: true
    });
  };

  //   componentDidMount() {
  //     this.search("");
  //   }

  render() {
    return (
      <div>
        <br />
        <div className="container card card-body">
          <h3>Search Criteria</h3>
          <div className="col-md-12 form-inline " style={{ padding: 8 }}>
            <div className="col-md-3">
              <input
                name="name"
                type="text"
                class="form-control"
                placeholder="Name"
                id="name"
                onChange={this.handleInputChange}
              />
            </div>
            <div className="col-md-3">
              <input
                name="username"
                type="text"
                class="form-control"
                placeholder="User Name"
                id="username"
                onChange={this.handleInputChange}
              />
            </div>
            <div className="col-md-3">
              <input
                name="mobile"
                type="number"
                class="form-control"
                placeholder="Mobile"
                id="number"
                onChange={this.handleInputChange}
              />
            </div>
            <div className="col-md-3">
              <input
                name="usercreateddate"
                type="text"
                class="form-control"
                placeholder="User Created Date"
                id="usercreateddate"
                onChange={this.handleInputChange}
              />
            </div>
          </div>
          <div>
            <button
              type="button"
              className="btn btn-primary"
              onClick={this.searchquery}
              style={{ marginLeft: "491px", marginTop: "15px" }}
            >
              Search
            </button>
          </div>
        </div>
      </div>
    );
  }
}

export default Search;

商店

import { EventEmitter } from "events";
import dispatcher from "../dispatcher/dispatcher";

class UserStore extends EventEmitter {
  constructor() {
    super();
    dispatcher.register(this.handleActions.bind(this));
    this.users = [
      {
        branch: "19",
        name: "Javcbvcsim11",
        username: "zxcv",
        mobile: "5645654",
        email: "demo@gmail.com111",
        address: "Demo vcbvcbAddress1",
        dob: "2020-11-06T00:00:00.000+0000"
      },
      {
        branch: "19",
        name: "Javcbvcsim11",
        username: "zxcv",
        mobile: "5645654",
        email: "demo@gmail.com111",
        address: "Demo vcbvcbAddress1",
        dob: "2020-11-06T00:00:00.000+0000"
      },
      {
        branch: "19",
        name: "Javcbvcsim11",
        username: "zxcv",
        mobile: "5645654",
        email: "demo@gmail.com111",
        address: "Demo vcbvcbAddress1",
        dob: "2020-11-06T00:00:00.000+0000"
      }
    ];

    console.log(" store constructor ");
  }

  createUser(newUser) {
    this.users.push(newUser);
    console.log("new  users lenght " + this.users.lenght);
    this.emit("change");
  }

  getAll() {
    return this.users;
  }
  handleActions(action) {
    switch (action.type) {
      case "RECEIVE_USERS": {
        this.users = action.users;
        this.emit("change");
        break;
      }
      case "CREATE_USER": {
        this.createUser(action.newUser);
        break;
      }
      case "SEARCH_USER": {
        console.log("sadsadsadsadsadsadsadsadsad");
        this.users = action.search;
        this.emit("change");

        break;
      }
    }
  }
}

export default new UserStore();

行动

从“../dispatcher/dispatcher”导入调度程序;

import { BASE_URL } from "../utils/AppConstants";

export function getUsersList() {
  console.log("getting the data! ");
  fetch(BASE_URL + "/users")
    .then(res => res.json())
    .then(
      result => {
        console.log("res " + result);
        dispatcher.dispatch({ type: "RECEIVE_USERS", users: result });
      },
      // Note: it's important to handle errors here instead of a catch() block so that
      // we don't swallow exceptions from actual bugs in components.
      error => {
        //  here manage error and close loading;
        console.log("getting error " + error);
      }
    );
}

export function createNewUser(user) {
  console.log("post the data!");
  fetch(BASE_URL + "/saveuser", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(user)
  })
    .then(res => res.json())
    .then(
      result => {
        dispatcher.dispatch({ type: "CREATE_USER", newUser: user });
      },
      // Note: it's important to handle errors here instead of a catch() block so that
      // we don't swallow exceptions from actual bugs in components.
      error => {
        //  here manage error and close loading;
        console.log("getting error " + error);
      }
    );
}

export function searchEvents(search) {
  const url =
    BASE_URL +
    `/searchuser?name=${search.name}&username=${search.username}&mobile=${
      search.mobile
    }&usercreateddate=${search.usercreateddate}`;
  console.log(url);
  fetch(url)
    .then(res => res.json())
    .then(
      result => {
        console.log("res jdjdjdjdjdj " + JSON.stringify(result));
        console.log("dfsfsf" + search);
        dispatcher.dispatch({ type: "SEARCH_USER", search: result });
      },
      // Note: it's important to handle errors here instead of a catch() block so that
      // we don't swallow exceptions from actual bugs in components.
      error => {
        //  here manage error and close loading;
        console.log("getting error " + error);
      }
    );
}

我在这里使用 react 助焊剂程序。也是通过 jquery 数据表显示的数据。 当我第一次搜索假设通过给用户名='something' 时发生错误,它在我的表中完美显示。当我单击数据表列名称或随附的搜索时,问题发生了,它更改为我已经提供的虚拟数据。有时也会抛出上述错误。如果有人可以提供帮助,那将是非常可观的。

最佳答案

当您执行以下操作时会出现此问题:

  1. 使用 React 渲染内容
  2. 然后,您使用外部脚本操作由 React 渲染的 DOM
  3. 现在在下一个渲染周期(重新渲染)中,React 找不到它之前渲染的 DOM 节点,因为它已经被外部脚本修改/删除了

我认为这段代码是罪魁祸首:

    $(document).ready(function() {
      $("#example").DataTable({
        ordering: true
      });
    });

有一篇很好的文章将 JQuery DataTableReact 一起使用 here .您可以引用它并尝试解决您的问题,或者您可以尝试将其替换为 DataTableReact 版本(例如:react-table)。

注意:避免同时使用ReactJQuery。从长远来看,这可能会产生问题。

关于javascript - react 错误 : NotFoundError: Failed to execute 'removeChild' on 'Node' : The node to be removed is not a child of this node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54341779/

相关文章:

babeljs - 自动检测 babel ext sublime

javascript - 创建 Assets 时内容丰富的内容管理 API 错误 422

node.js - 在本地主机中登录但在 Heroku 中部署时出现错误 "secret option required for sessions"

javascript - 将 JSON/Date(1238626800000)/转换为 Unix 时间戳

javascript - 访问链中先前 Promise 的数据

asp.net - 如何在 JavaScript 中检查 IsPostBack?

javascript - 显示文件夹中最新的图像,自动刷新

javascript - 迭代 JSX 中对象内部的数组给出 undefined

javascript - 往返商店的通量事件?

javascript - SASS child rule setting inside based on parent 下?