简体   繁体   English

为什么在组件安装之前Axios会继续发送请求?

[英]Why does Axios keep sending requests before component mounts?

I have an app with React front and Spring backend. 我有一个带有React前端和Spring后端的应用程序。 I use Axios to fetch from the back. 我使用Axios从背面获取。 I have 2 class components with tables and I can access them via a menu component (in componentDidMount and componentDidUpdate only). 我有2个带有表的类组件,并且可以通过菜单组件(仅在componentDidMount和componentDidUpdate中)访问它们。 I use all the possible precautions against infinite loops (loaded state and isMounted with a custom name). 我使用所有可能的预防措施来防止无限循环(加载状态和使用自定义名称的isMounted)。 It works in the first component which I access after logging in. However, the second component (which is logically the same as the first, just has another entity to fetch) keeps requesting with axios until i go there (i see it in the network tab of my browser). 它在登录后访问的第一个组件中起作用。但是,第二个组件(与第一个组件在逻辑上相同,只是有另一个要提取的实体)一直向axios发出请求,直到我到达那里为止(我在网络中看到了它)浏览器的标签)。 Why can it be? 为什么会这样呢? it is definitely not mounted and console.logs don't work from there but while I'm on first it keeps requesting on and on (and it doesn't receive anything I guess, it is 0 bytes at this time) 它肯定没有挂载并且console.logs从那里不起作用,但是当我第一次启动时,它会不断地请求(并且我没有收到任何东西,我猜这是0字节)

import React, { Component } from 'react'
import {Link} from 'react-router-dom';
import axios from 'axios'
import "react-table/react-table.css";
import ReactTable from 'react-table';
import {Button, ButtonToolbar} from 'react-bootstrap';
import { LinkContainer } from "react-router-bootstrap";
import AddCalculationsModal from './AddCalculationsModal';
import UpdateCalculationsModal from './UpdateCalculationsModal';
import Cluster from './Cluster';
import Select from 'react-select/src/Select';

export default class Calculations extends Component {
  isCMounted = false;
  constructor(props) {
    super(props)

    this.state = {
        items: [],
        selected: null,
        addModalShow: false,
        updateModalShow: false,
        updateId: null,
        buttonOn: false,
        page: 0,
        elements: 0,
        loaded: false
    }
}

  componentDidMount() {
    this.isCMounted = true;
    if(!this.state.loaded){
      this.load();
    }
  };

  componentDidUpdate() {
    if(!this.state.loaded){
      this.load();
    }
  };

  componentWillUnmount(){
    this.isCMounted = false;
  }

  increasePage = () => {
    this.setState({
      page: this.state.page + 1
    })
  }

  decreasePage = () => {
    this.setState({
      page: this.state.page - 1
    })
  }

  load = async () => {
    await axios.get(`calculations?page=${this.state.page}&elements=${this.state.elements}`)
    .then(res => {
      if (this.isCMounted && this.state.items.id === res.data.id){
        this.setState({items: res.data})
      }
    });
    if(this.state.selected != null && this.isCMounted) {
      this.setState({buttonOn: true})
    }
    this.setState({loaded: true})
  }

  setId = (id) => {
    const idValue = this.state.items[id].id;
    if (this.isCMounted)
      this.setState({updateId: idValue});
  }

  deleteRow = (id) => {
    const index = this.state.items.findIndex(item => {
      return item.id === this.state.items[id].id})
      const idValue = this.state.items[id].id

    axios.delete(`calculations/${idValue}`).then(
      res => {
        this.load();
      }
    )

    this.state.items.splice(index, 1)
    this.load();
  }

  render() {
    let addModalClose = () => this.setState({addModalShow: false});
    let updateModalClose = () => this.setState({updateModalShow: false});
    return (
      <div>
        <h3>Calculations</h3>
        <ReactTable
          columns={
            [
              {
                Header: "ID",
                accessor: "id"
              },
              {
                Header: "Name",
                accessor: "name"
              },
              {
                Header: "Creation Date",
                accessor: "dateCreate"
              },
              {
                Header: "Update Date",
                accessor: "dateUpdate"
              },
              {
                Header: "User",
                accessor: "userId"
              }
            ]  
          }
          data={this.state.items}
          filterable
          showPagination={false}
          getTrProps={(state, rowInfo) => {
            if (rowInfo && rowInfo.row) {
              return {
                onClick: (e) => {
                  this.setState({
                    selected: rowInfo.index
                  })
                },
                style: {
                  background: rowInfo.index === this.state.selected ? '#00afec' : 'white',
                  color: rowInfo.index === this.state.selected ? 'white' : 'black'
                }
              }
            }else{
              return {}
            }
          }}
          >
      </ReactTable>
      <ButtonToolbar>
      <Button variant="primary" onClick={() => {
          this.decreasePage();
          this.load();
        }}>PREVIOUS PAGE</Button>
      <Button variant="primary" onClick={() => {
        this.increasePage();
        this.load();
      }}>NEXT PAGE</Button>
      </ButtonToolbar>
      <ButtonToolbar>
        <Button variant="primary" onClick={() => this.setState({addModalShow: true})}>
          Add Calculation
        </Button>
        <Button variant="primary" onClick={() => {
          this.setId(this.state.selected);
          this.setState({updateModalShow: true})}} disabled={this.state.buttonOn ? false : true}>
          Update Calculation
        </Button>
        <Button variant="danger" onClick={() => {
          this.deleteRow(this.state.selected);
        }}>DELETE</Button>

        <Link to={`/calculations/${this.state.items[this.state.selected] && this.state.items[this.state.selected].id}`}>
          <Button variant="warning" disabled={this.state.buttonOn ? false : true}>Cluster</Button>
        </Link>

        <AddCalculationsModal 
          show={this.state.addModalShow}
          onHide={addModalClose}
          calculation={this.state.items[this.state.selected]}
          />

        <UpdateCalculationsModal 
          show={this.state.updateModalShow}
          onHide={updateModalClose}
          calculation={this.state.items[this.state.selected] && this.state.items[this.state.selected].id}
          calcname={this.state.items[this.state.selected] && this.state.items[this.state.selected].name}
          />

      </ButtonToolbar>
      </div>
    )
  }
}

And

import React, { Component } from 'react'
import axios from 'axios'
import "react-table/react-table.css";
import ReactTable from 'react-table';
import {Button, ButtonToolbar} from 'react-bootstrap';
import AuthenticationService from '../service/AuthenticationService';

export default class Calculations extends Component {
  isCMounted = false;
  constructor(props) {
    super(props)

    this.state = {
        items: [],
        selected: null,
        updateId: null,
        loaded: false
    }
}

  componentDidMount() {
    this.isCMounted = true;
    if(!this.state.loaded) {
      this.load();
    }
  };

  componentDidUpdate() {
    if(!this.state.loaded) {
      this.load();
    }
  };

  componentWillUnmount() {
    this.isCMounted = false;
  }

  load = async () => {
    if(this.isCMounted && !this.state.loaded) {
    await axios.get('calculation-types')
    .then(res => {
      console.log(this.isCMounted)
      if (this.isCMounted && this.state.items.id === res.data.id){
      this.setState({items: res.data})
      }
    });
  this.setState({loaded: true})
  }
  }

  setId = (id) => {
    const idValue = this.state.items[id].id;
    if (this.isCMounted)
    this.setState({updateId: idValue});
  }

  render() {
    return (
      <div>
        <h3>Calculation Types</h3>
        <ReactTable
          columns={
            [
              {
                Header: "ID",
                accessor: "idType",
                width: 100,
                minWidth: 100,
                maxWidth: 100          
              },
              {
                Header: "Name",
                accessor: "name"
              }
            ]  
          }
          data={this.state.items}
          filterable
          showPagination={false}
          getTrProps={(state, rowInfo) => {
            if (rowInfo && rowInfo.row) {
              return {
                onClick: (e) => {
                  this.setState({
                    selected: rowInfo.index
                  })
                },
                style: {
                  background: rowInfo.index === this.state.selected ? '#00afec' : 'white',
                  color: rowInfo.index === this.state.selected ? 'white' : 'black'
                }
              }
            }else{
              return {}
            }
          }}
          >
      </ReactTable>
      </div>
    )
  }
}

are my components. 是我的组成部分。 Menu is a normal link. 菜单是正常链接。 after login i appear on the first with menu on top. 登录后,我出现在第一个菜单顶部的菜单上。

Have you tried moving this.setState({loaded: true}) into the axios response callback block? 您是否尝试过将this.setState({loaded: true})移到axios响应回调块中? Since you're awaiting the fetch request, I wonder if the this.setState({items: res.data} that you have in the callback block is causing an infinite componentDidUpdate loop that causes load to be repeatedly called without ever having the chance to arrive at the this.setState({loaded: true}) in the final line of load . 由于您正在等待提取请求,因此我想知道您在回调块中具有的this.setState({items: res.data}是否正在引起无限的componentDidUpdate循环,该循环导致反复调用load而没有机会在到达this.setState({loaded: true})中的最后一行load

load = async () => {
  if(this.isCMounted && !this.state.loaded) {
    await axios.get('calculation-types')
      .then(res => {
        console.log(this.isCMounted)
        if (this.isCMounted && this.state.items.id === res.data.id){
          this.setState({ items: res.data, loaded: true })
        }
      });
  }
}

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

相关问题 在组件挂载之前运行的 ReactJS 内联函数 - ReactJS In-Line Function Running Before Component Mounts ReactJs:由于不推荐使用 componentWillMount,如何在组件安装之前执行代码? - ReactJs: How to execute code before a component mounts since componentWillMount is deprecated? 为什么我的 Axios post 函数总是返回 401? - Why does my Axios post function keep returning 401? 为什么回调前的持续时间不断增加? - Why does the duration before the callback keep increasing? 为什么这个 React 组件一直在重新渲染? - Why does this React component keep re rendering? 为什么 axios.get(url).data 不起作用? (axios GET 请求和属性访问器;JavaScript) - Why does axios.get(url).data not work? (axios GET requests and property accessors; JavaScript) 关于使用 Axios 发送多个请求的查询 - React - A query on sending multiple requests using Axios - React Axios HTTP 请求不发送到 Fastify 后端 - Axios HTTP requests not sending to Fastify backend axios 在反应中发送所有请求的问题 - axios problem with sending all requests in react react-router:嵌套路由组件在父路由组件之前安装? - react-router: Nested route component mounts before parent route component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM