Undefined is not an object evaluating this.state/this.props

前端 未结 4 889
心在旅途
心在旅途 2021-01-28 16:20

How do I bind a function outside of scope in React Native? I\'m getting the errors:

undefined is not an object evaluating this.state   

&

4条回答
  •  后悔当初
    2021-01-28 16:46

    This is happening because, the function inside the map method creates a different context. You can use arrow functions as the callback in the map method for lexical binding. That should solve the issue you are having.

    renderGPSDataFromServer =() => {
    
        const {loaded} = this.state;
        const {state} = this.state;
    
        return this.state.dataArr.map((data, i) => {
          return(
            
    
              
                
                View Video
                
              
    
              
                {i}
                
                  
                  {Number(data.lat).toFixed(2)}
                  {Number(data.long).toFixed(2)}
                
                
                {this.calcRow(55,55).bind(this)}
                
              
    
            
          );
        });
      }

    Also, once you've used arrow functions in the class function definition you don't need to bind them in constructor like:

    constructor(props) {
      super(props);
      this._customMethodDefinedUsingFatArrow = this._customMethodDefinedUsingFatArrow.bind(this)
    }

    Also, once you have defined class functions as arrow functions, you don't need to use the arrow functions while calling them either:

    class Example extends React.Component {
      myfunc = () => {
        this.nextFunc()
      }
    
      nextFunc = () => {
        console.log('hello hello')
      }
    
      render() {
        // this will give you the desired result
        return (
          
        )
        
        // you don't need to do this
        return (
           this.myFunc()} />
        )
      }
    }

提交回复
热议问题