Диспетчерский вызов внутри axios вызывает DOMException: не удалось выполнить «removeChild» при ошибке «Node» - PullRequest
0 голосов
/ 30 августа 2018

Я получаю вызов API новостей, когда пользовательские фильтры раскрываются в окне навигации. В действиях создателей, которые выбирают API, я переключаю состояние загрузки. Перед вызовом API я меняю значение true и переключаю это состояние после получения ответа. от api. Но проблема в том, что, когда я отправляю действия, которые пытаются завершить состояние загрузки внутри ответного обратного вызова axios, браузер перестает работать, и он показывает эту ошибку. Я понятия не имею об этом сообщении об ошибке и как оно связано с избыточным рассылка. Может ли кто-нибудь помочь мне с этим?

react-dom.development.js:8625 Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
    at removeChild (http://localhost:3000/static/js/bundle.js:16854:18)
    at unmountHostComponents (http://localhost:3000/static/js/bundle.js:23012:9)
    at commitDeletion (http://localhost:3000/static/js/bundle.js:23057:5)
    at commitAllHostEffects (http://localhost:3000/static/js/bundle.js:23646:11)
    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:8329:14)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:8367:16)
    at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:8416:29)
    at commitRoot (http://localhost:3000/static/js/bundle.js:23798:7)
    at completeRoot (http://localhost:3000/static/js/bundle.js:24848:34)
    at performWorkOnRoot (http://localhost:3000/static/js/bundle.js:24793:9)
    at performWork (http://localhost:3000/static/js/bundle.js:24712:7)
    at performSyncWork (http://localhost:3000/static/js/bundle.js:24684:3)
    at interactiveUpdates$1 (http://localhost:3000/static/js/bundle.js:24949:7)
    at interactiveUpdates (http://localhost:3000/static/js/bundle.js:10379:10)
    at dispatchInteractiveEvent (http://localhost:3000/static/js/bundle.js:12762:3)
removeChild @ react-dom.development.js:8625
unmountHostComponents @ react-dom.development.js:14783
commitDeletion @ react-dom.development.js:14828
commitAllHostEffects @ react-dom.development.js:15417
callCallback @ react-dom.development.js:100
invokeGuardedCallbackDev @ react-dom.development.js:138
invokeGuardedCallback @ react-dom.development.js:187
commitRoot @ react-dom.development.js:15569
completeRoot @ react-dom.development.js:16619
performWorkOnRoot @ react-dom.development.js:16564
performWork @ react-dom.development.js:16483
performSyncWork @ react-dom.development.js:16455
interactiveUpdates$1 @ react-dom.development.js:16720
interactiveUpdates @ react-dom.development.js:2150
dispatchInteractiveEvent @ react-dom.development.js:4533
index.js:2178 The above error occurred in the <i> component:
    in i (at Post.js:45)
    in div (at Post.js:44)
    in div (at Post.js:43)
    in div (at Post.js:42)
    in div (at Post.js:37)
    in div (at Post.js:36)
    in Post (created by Connect(Post))
    in Connect(Post) (at Posts.js:32)
    in div (at Posts.js:31)
    in Posts (created by Connect(Posts))
    in Connect(Posts) (at Home.js:13)
    in div (at Home.js:12)
    in div (at Home.js:11)
    in div (at App.js:7)
    in App (at Home.js:10)
    in Home (created by Route)
    in Route (at index.js:23)
    in Switch (at index.js:22)
    in div (at index.js:21)
    in Router (created by BrowserRouter)
    in BrowserRouter (at index.js:20)
    in Provider (at index.js:19)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit fb.me/react-error-boundaries to learn more about error boundaries.

Вот действие создателей, fetchPosts.js

import axios from 'axios';

function fetchPosts(){

    return (dispatch,store) => {
        let {category} = store()

        let url = `https://newsapi.org/v2/everything?q=${category.selectedCategory}&apiKey=90581a0a53f54c4a85c7b743c74b24fd&pageSize=6&page=1`;
        dispatch({type:'postLoadingStart'});

        axios.get(url).then((res) => {
        dispatch({type:'postLoadingEnd'});
        })

      };
}

export default fetchPosts;

Вот мой загрузочный редуктор, loadingPosts.js

const initialState = {
    loading: false
}
function loadingPosts(state = initialState, action){

    switch(action.type){
    case 'postLoadingStart':
      return {
        loading: true
      };
      case 'postLoadingEnd':
      console.log("post loading end");
      return {
        loading: false
      };
    case 'test':
    console.log("Here");
      return {
          ...state
      }
    default:
      return state;
  }
  return state
}

export default loadingPosts;

Вот мой компонент NavigationDropDown, который содержит раскрывающийся список для фильтрации, NavDropDown.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import fetchPosts from '../actions/fetchPosts';

class NavDropDown extends Component {
    filterDropDown = ()=> {
       this.props.toggleDropDown();
    }

    filterCategory= (category)=>{
        this.props.filterCategory(category);
        this.props.fetchPosts();
    }
   renderDropDownLinks = ()=>{

    let {categories,selectedCategory} = this.props.category;

       return Object.keys(this.props.category.categories).map(
           (category)=> <a key={category} className={`dropdown-item ${categories[category] == selectedCategory?'is-active':""}`} onClick={()=>this.filterCategory(category)}>
           {categories[category]} 
         </a>
       )
   }

    render() {

    return (
        <div>
        <div className={`category-drop-down dropdown ${this.props.category.filterOpen?"is-active":"'"}`}>
        {/* toggle with is-active */}
  <div className="dropdown-trigger" onClick={this.filterDropDown}>
    <button className="button" aria-haspopup="true" aria-controls="dropdown-menu" >
      <span>{this.props.category.selectedCategory}</span>
      <span className="icon is-small">
        <i className="fas fa-angle-down" aria-hidden="true"></i>
      </span>
    </button>
  </div>

  <div className="dropdown-menu" id="dropdown-menu" role="menu">
    <div className="dropdown-content">
      {this.renderDropDownLinks()}
    </div>
  </div>
</div>
</div>
    );
  }



}

const mapStateToProps = (state) => ({
category: state.category
})

const mapDispatchToProps = dispatch => ({
    toggleDropDown: () => {
    dispatch({type:'toggle_dropdown'});
   },
   filterCategory: (category)=>{
       dispatch({type:'filter_category',category:category})
       dispatch({type:'toggle_dropdown'});
   },
   fetchPosts: ()=> dispatch(fetchPosts())
});

export default connect(mapStateToProps,mapDispatchToProps)(NavDropDown)

Вот мой редуктор категорий, который меняет категорию, category.js

const categories = {
    technology: "Technology",
    business: "Business",
    sports:"Sports",
    entertainment:"Entertainment",
    science:"Science",
    health:"Health"
}

const initialState = {
    categories: categories,
    selectedCategory: categories.technology,
    filterOpen: false
}
function category(state = initialState, action){

     switch(action.type){
     case 'filter_category':

       return {
         ...state,
         selectedCategory:categories[action.category]
       };
     case 'toggle_dropdown':{
        return {
          ...state,
          filterOpen: !state.filterOpen
        };
     }
     default:
     return {
        ...state,
      };
   }
  return state
}

export default category;
...