javascript - 如何取消 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;
解决方案
Actions 组件中的 componentDidMount() 方法被再次调用,因为您的父组件被重新渲染,子组件也将被重新渲染。要阻止这种情况,请将您的 Actions 组件改为 Pure 组件。只有当该组件的状态或道具发生变化时,才会重新渲染 Pure 组件。 代替
class Actions extends React.Component{
和
class Actions extends React.PureComponent {
希望能帮助到你!!
推荐阅读
- javascript - 在客户端打开带有附件的 Outlook 应用程序
- javascript - 函数返回 bool 时如何使用不同的 SweetAlert?
- types - 如何派生语言的语法(来自《类型和编程语言》一书)?
- c++ - opencv4+ 中 cvGetWindowHandle() 的替代方案
- linux - 如何将嵌套命令传递给 ssh 以在命令行中运行?
- c# - 从 Windows 窗体将文件上传到网站
- python - 如何组合 DataFrame 以创建带有附加列的新 DataFrame?
- python - 分区中唯一子串的最大数量
- python - AttributeError:“str”对象没有属性“train”
- python - 如何合并具有相同值的csv行中的特定单元格