首页 > 解决方案 > 如何取消 ReactJS 组件中 componentDidMount() 的多重调用?

问题描述

我创建了一个组件DATA,它具有componentDidMount()函数来从 API 获取数据。在此之后,我将它导入到主要组件中。主要组件有一个渲染方法,其中我有一个简单的结构:第一个 div - 一些信息和导入的组件数据,第二个 div 是一个打开模式的按钮,它有一些文本和关闭这个模式对话框的按钮。我读过componentDidMount()在组件渲染后只调用一次。但是,当我按下按钮同时打开我的模态页面时,再次调用componentDidMount() 。我需要的是componentDidMount()当我打开模态框时不要运行。但仅在页面呈现或刷新时运行。

主要成分

import React from "react";
import Modal from '../components/modal/form'
import Actions from '../data/Actions'

class MainPage extends React.Component{
    constructor(){
        super();

        this.state = {
            show: false,

        };

        this.showModal = this.showModal.bind(this); 
        //this.setSearchTopStories = this.setSearchTopStories.bind(this);

    };

    showModal = e => {
        this.setState({
          show: !this.state.show
        });
    };



    render(){

        return <div>
            <div className="topDescribtion">
                <h2>descr</h2>
                <Actions />
            </div>
            <div className="btnNewTransaction">
                <button onClick={e => {
                    this.showModal();
                }}>
                    show Modal
                </button>
                <Modal onClose={this.showModal} show={this.state.show}>
                    Mdl--
                </Modal>
            </div>
            <div className="transactionList"></div>
        </div>
    }
}  
export default MainPage;

数据组件

import React, { Component } from "react";
import Modal from '../components/modal/form'

const PATH_BASE = 'my URL which I give data in JSON format and it works fine';

class Actions extends React.Component{
    constructor(){
        super();
        this.state = {
            result:null
        };
        this.setSearchTopStories = this.setSearchTopStories.bind(this);
    }
    setSearchTopStories(result) {
        this.setState({ result });
    };
    componentDidMount() {        
        fetch(`${PATH_BASE}`)
            .then(response => response.json())
            .then(result => this.setSearchTopStories(result))
        .catch(error => error); 
    };
    render(){
        const { searchTerm, result } = this.state;
        console.log(result);
        return <div></div>;
    }
}

export default Actions;

标签: javascriptreactjs

解决方案


Actions 组件中的 componentDidMount() 方法被再次调用,因为您的父组件被重新渲染,子组件也将被重新渲染。要阻止这种情况,请将您的 Actions 组件改为 Pure 组件。只有当该组件的状态或道具发生变化时,才会重新渲染 Pure 组件。 代替

class Actions extends React.Component{

class Actions extends React.PureComponent {  

希望能帮助到你!!


推荐阅读