最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactJs : How to reload a component onClick - Stack Overflow

programmeradmin7浏览0评论

I am new to React and am still learning it. I have a component Requirements which I would like to reload everytime getDocFinancialInfo () is called by clicking on the event. The issue is that it loads the correct information the first time but does not refreshes it on subsequent clicks. Any help or suggestion would be most welcome.

    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()}>&times;</span>
                        <Requirements />
                      </div>
                    </div>

                .........
          </div>
        )
      }
    }

    export default UploadDocument

I am new to React and am still learning it. I have a component Requirements which I would like to reload everytime getDocFinancialInfo () is called by clicking on the event. The issue is that it loads the correct information the first time but does not refreshes it on subsequent clicks. Any help or suggestion would be most welcome.

    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()}>&times;</span>
                        <Requirements />
                      </div>
                    </div>

                .........
          </div>
        )
      }
    }

    export default UploadDocument
Share Improve this question asked Nov 8, 2018 at 10:36 Abhinav MehrotraAbhinav Mehrotra 6132 gold badges9 silver badges18 bronze badges 2
  • React renders it's view based on state & props,. state is something that changes over time, so what your doing is changing something over time, so logically you should be calling setState. If state cannot be implied, then there is also forceUpdate reactjs.org/docs/react-component.html#forceupdate But if your not using setState, you might want to think out the logic a bit more. One area where you don't use setState, is when implementing Single Source Of Truth, but for that you would be using something like Redux. – Keith Commented Nov 8, 2018 at 10:40
  • Change the state it will reload. – Ilyas karim Commented Nov 8, 2018 at 10:59
Add a comment  | 

3 Answers 3

Reset to default 10

You can change the key prop given to a component in order to unmount it and mount a new one.

You could keep a random value in your state that you randomise again when getDocFinancialInfo is called and use this value as the key for Requirements.

Example

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>

As mentioned above - change key value is a great idea But instead of using Math.random I prefer using new Date() value to be sure that key is changed anyway :)

You can use vanilla Javascript to call reload method window.location.reload(false)

<button onClick={() => window.location.reload(false)}>Click to reload!</button>
发布评论

评论列表(0)

  1. 暂无评论