【发布时间】:2020-06-30 11:41:04
【问题描述】:
我创建了一个组件 DATA,它具有 componentDidMount() 函数来从 API 获取数据。在此之后,我将它导入到 main 组件中。主要组件有一个渲染方法,其中我有一个简单的结构:第一个 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;
DATA组件
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;
【问题讨论】:
标签: javascript reactjs