简体   繁体   中英

How to correctly use componentDidMount and componentDidUpdate in React.js?

I have a problem. I want to search for an index based on a url. Everything is sent to the components as it should, but there is an error after loading:

Cannot read property 'indexOf' of undefined

Data sent from JSON is sure to be transmitted and received correctly and is correctly assigned. The problem is most likely caused by badly applied 'componentDidMount' and 'componentDidUpdate'. How should it look correctly?

The data sent based on the URL of the page is 'this.props.brand'

Code:

class CarPage extends Component {
   state = {
       isLoading: true,
       carData: [],
       id: null
   }
   findMyIndex = () => {
       this.setState({
           id: this.carData.indexOf(this.props.brand),
       })
   }
   componentDidUpdate() {
       this.findMyIndex()
   }
   componentDidMount() {
       fetch("/data.json")
           .then(response => response.json())
           .then(data => {
               this.setState({
                   carData: data,
                   isLoading: false,
               })
           })

   }
   render() {
       return (
           <>
               {!this.state.isLoading && (
                   <p>{this.state.carData[this.state.id].model}</p>
               )}
           </>
       );
   }
}

export default CarPage;

You don't need componentDidUpdate lifecycle method at all. You can do it like this:

 class CarPage extends Component {
   state = {
       isLoading: true,
       carData: [],
       id: null
   }
   findMyIndex = () => {
       return this.state.carData.map(el => el.brand).indexOf(this.props.brand);
   }
   componentDidMount() {
       fetch("/data.json")
           .then(response => response.json())
           .then(data => {
               this.setState({
                   carData: data,
                   isLoading: false,
               })
           })

   }
   render() {
       return (
           <>
               {!this.state.isLoading && (
                   <p>{this.state.carData[this.findMyIndex(this.props.brand)].model}</p>
               )}
           </>
       );
   }
}

export default CarPage;

It seems that findMyIndex returns -1 and this.state.carData[this.state.id] is equal to undefined . Check if CarData indeed has a this.props.brand entry.

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