简体   繁体   中英

React - ref's current function fails on if statement

I am encountering a very wierd issue with React createRef

I call a ref and it only works in an else branch of an if/else statement.

if I remove the if statement, the ref does not work, and if the function goes to the IF path, it does not work too.

Here is a snippet.

sendFetch("/api/cases?q=" + JSON.stringify(query_payload), "", "GET").then(
  data => {
    this.fetchedData = data;
    console.log(data.count + " results found")
    //populate the table with results
    if (data.count === "0" || data.status === "failed") {
      console.log("NOT FOUND")
      this.tableRef.current.loadTablewithNewData(false)
      //NOT WORKING
    } else {
      //reload the table component with the new data
      this.tableRef.current.loadTablewithNewData(data.context)
      //WORKING
    }
  }
)

When the IF path is followed, or I remove the if/else alltogether and call the ref function right away, REACT shows this error × Unhandled Rejection (TypeError): Cannot read property 'loadTablewithNewData' of null

Did you check to see if the element you've added a ref to actually exists in the DOM when you make the request?

Unhandled Rejection (TypeError): Cannot read property 'loadTablewithNewData' of null

This error is given only if the element is not present in the DOM when you try to access it. The code you've posted here works as expected. Check if the element exists before you try to manipulate it directly in the DOM

 if(this.tableRef.current){ // It would be null if it doesn't exist if (data.count === "0" || data.status === "failed") { console.log("NOT FOUND") this.tableRef.current.loadTablewithNewData(false) } else { //reload the table component with the new data this.tableRef.current.loadTablewithNewData(data.context) } } else { console.log('Table not present in the DOM') }

Found it.

It appears that the reason why it happened is because of the way I render the component. I have a conditional statement that renders a different component the first time I load the page. the else statement worked because the else path will only be followed when the page was not loaded the first time.

So what happened is the if path will try to call a ref for a DOM that has not been rendered yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM