反应:TypeError:无法读取未定义的属性"Item" [英] React : TypeError: Cannot read property 'Item' of undefined
问题描述
我想在新状态道具中访问状态/属性的值.实际上,我已经具有状态属性,在其中存储Item = 5的值,并在UrlParam中创建要存储URL的位置,但是我需要URL属性中的项数字值.我是React的新手,请有人帮我怎么做?
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 ?
当我遇到错误 TypeError:无法读取未定义的属性'Item'
时,有人可以帮助我吗?
When I getting Error TypeError: Cannot read property 'Item' of undefined
, Could someone please help me ?
代码
this.state={
Item : 5,
skip:0,
urlParams:`http://localhost:8001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
}
推荐答案
作为另一个答案,您似乎正在尝试在赋值表达式 this之前使用
已完成. this.state.Item
.state = {...}
As another answer mentioned, it looks like you are trying to use this.state.Item
before the assignment expression this.state={...}
is complete.
也就是说,您似乎希望 urlParams
始终保持最新状态,并使用 Item
和 skip
.在这种情况下,您可能希望将其实现为帮助函数,而不是 state
的属性.
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>
这篇关于反应:TypeError:无法读取未定义的属性"Item"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!