Skip to content Skip to sidebar Skip to footer

React : Typeerror: Cannot Read Property 'item' Of Undefined

I want to access the value of state/property in new state prop. Actually I have already state property where I am storing value of Item=5 and I create UrlParam Where I am storing U

Solution 1:

As another answer mentioned, it looks like you are trying to use this.state.Item before the assignment expression this.state={...} is complete.

That said, it looks a bit like you want urlParams to always stay up-to-date with the new values of Item and skip. If that's the case, you may want to implement it as a helper function instead of a property of state.

classExampleextendsReact.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      Item: 5,
      skip: 0
    }
    
    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return`http://localhost:8001/parties?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }
  
  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div><ahref={this.urlParams()}>Example link</a><pre>{this.urlParams()}</pre><buttononClick={this.handleClick}>Change link</button></div>
    )
  }
}

    
ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><divid="my-example"></div>

Solution 2:

When the value for urlParams is interpolated this.state is not defined yet.

Either define Item and skip as a separate variables or set this.state.urlParams afterwards:

constItem = 5;
const skip = 0;
 this.state={
  Item,
  skip,
  urlParams:`http://localhost:8001/parties?filter[limit]=${(Item)}&&filter[skip]=${skip}`
}

or

this.state={
  Item : 5,
  skip:0
};
  this.state.urlParams = `http://localhost:8001/parties?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`;

Post a Comment for "React : Typeerror: Cannot Read Property 'item' Of Undefined"