[英]ReactJs : How to reload a component onClick
我是 React 的新手并且仍在学习它。 我有一个组件要求,每次单击事件调用getDocFinancialInfo () 时,我都想重新加载它。 问题是它第一次加载了正确的信息,但在后续点击时不会刷新它。 任何帮助或建议将是最受欢迎的。
import React, { Component } from 'react';
import './UploadDocument.css'
import spinner from './spinner.gif'
import verified from './verified.png';
import notverified from './not-verified.png';
import Requirements from './Requirement.js'
class UploadDocument extends Component{
constructor(props) {
super(props);
this.state = {
application: [],
document:[],
id: null,
files: [],
docFinacialInfo: [],
uploaded: null,
fileInfo: []
}
}
componentDidMount() {
......
}
getDocFinancialInfo = async(docId) => {
sessionStorage.setItem('docId',docId);
var req = document.getElementById('requirements');
req.style.display = "block";
}
render(){
......
if(notVerifiedStatus > 0){
docVerificationStatus[index] = <td className="red"><img src={notverified} alt="Not Verified"/><label onClick={()=>this.getDocFinancialInfo(docId)}>Not Verified{docId}</label></td>;
}else{
docVerificationStatus[index] = <td className="green"><img src={verified} alt="Verified" /><label>Verified</label></td>;
}
console.log("Not Verified >>>"+notVerifiedStatus);
});
......
return(
<div>
.........
<div id="requirements">
<div id="requirements-content">
<span className="close" onClick={()=>this.closeRequirements()}>×</span>
<Requirements />
</div>
</div>
.........
</div>
)
}
}
export default UploadDocument
您可以更改提供给组件的key
prop,以便卸载它并安装一个新组件。
您可以在您的状态中保留一个随机值,在调用getDocFinancialInfo
时再次随机化,并使用该值作为Requirements
的key
。
例子
class Requirements extends React.Component { state = { count: 0 }; componentDidMount() { this.interval = setInterval(() => { this.setState(({ count }) => ({ count: count + 1 })); }, 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return <div> {this.state.count}</div>; } } class UploadDocument extends React.Component { state = { requirementKey: Math.random() }; getDocFinancialInfo = docId => { this.setState({ requirementKey: Math.random() }); }; render() { return ( <div> <Requirements key={this.state.requirementKey} /> <button onClick={this.getDocFinancialInfo}> Reload </button> </div> ); } } ReactDOM.render(<UploadDocument />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
如上所述 - 更改键值是个好主意但是我更喜欢使用 new Date() 值而不是使用 Math.random 来确保键值无论如何都被更改了:)
您可以使用 vanilla Javascript 调用reload
方法window.location.reload(false)
<button onClick={() => window.location.reload(false)}>Click to reload!</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.