我想访问新状态属性中状态/属性的值。实际上,我已经有状态属性,在其中存储 Item=5 的值,并在存储 URL 的位置创建 UrlParam,但我需要 URL 属性中的 Item 数值。我是 React 新手,请有人帮助我该怎么做?
当我收到错误 TypeError: Cannot read property 'Item' of undefined
时,有人可以帮助我吗?
代码
this.state={
Item : 5,
skip:0,
urlParams:`http://localhost:8001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
}
最佳答案
正如另一个答案提到的,看起来您正在尝试在赋值表达式 this.state={...}
完成之前使用 this.state.Item
.
也就是说,看起来有点像您希望 urlParams
始终与 Item
和 skip
的新值保持同步>。如果是这种情况,您可能希望将其实现为辅助函数,而不是 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>
关于javascript - react : TypeError: Cannot read property 'Item' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55269760/