javascript - react : TypeError: Cannot read property 'Item' of undefined

标签 javascript reactjs ecmascript-6

我想访问新状态属性中状态/属性的值。实际上,我已经有状态属性,在其中存储 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 始终与 Itemskip 的新值保持同步>。如果是这种情况,您可能希望将其实现为辅助函数,而不是 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/

相关文章:

javascript - 现有应用程序上的 React Native 电影教程的图像未在设备上显示

javascript - 在 Angular 2 中使用 require 设置 templateUrl 时出现错误

javascript - 由于 ES2015 模板文字导致的 Webpack 错误 - "Unterminated string constant"

javascript - 为什么将 javascript promise 传递给 `then` 会导致奇怪的行为?

reactjs - 如果 initialValue 更改,则更新 antd 表单

javascript - 打开 AI 示例代码不起作用 "Await is only valid in async functions and the top level bodies of modules"

javascript - 使用路由器管理图像资源的获取请求

javascript - 将裁剪后的图像发送到客户端上的 ajax 数据库和服务器上的 PHP

php - 我需要一个 PHP 脚本来解密由 生成的 RSA 加密字符串

reactjs - 如何在表单渲染后预填充 "redux form' s"输入字段