问题
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 URL but I need Item numeric value in URL property. I am new to React , Somebody please help me how to do this ?
When I getting Error TypeError: Cannot read property 'Item' of undefined
, Could someone please help me ?
Code
this.state={
Item : 5,
skip:0,
urlParams:`http://localhost:8001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
}
回答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
.
class Example extends React.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>
<a href={this.urlParams()}>Example link</a>
<pre>{this.urlParams()}</pre>
<button onClick={this.handleClick}>Change link</button>
</div>
)
}
}
ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="my-example"></div>
回答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:
const Item = 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}`;
来源:https://stackoverflow.com/questions/55269760/react-typeerror-cannot-read-property-item-of-undefined