【问题标题】:React : Uncaught (in promise) Error: Request failed with status code 400反应:未捕获(承诺)错误:请求失败,状态码为 400
【发布时间】:2019-08-03 11:21:03
【问题描述】:

我正在使用 ReactJS,我想为我的应用程序创建分页。当我单击下一步按钮时,我收到此错误 Uncaught (in promise) Error: Request failed with status code 400 。我正在通过在 Loopback 中构建的 API 获取页面数据。有人可以帮我解决这个问题吗,因为我是新手,对 ReactJS 不太了解

代码

        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:3001/meetups?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' ))

【问题讨论】:

  • 您的初始id 是10,您是否每次点击下一个按钮时都想获得id+1?似乎您的 btnClick func 正在从分页组件中获取价值。不要认为e.target.value 有任何价值。
  • 其实我想在第二次点击时加载数据10-20 但问题是我无法加载数据

标签: javascript reactjs ecmascript-6 axios


【解决方案1】:

你的btnClick 函数:

btnClick(e) {
  const id = e.target.value;
  this.setState({
       id: id+1
    },
    () => this.getData()
  )
}

不会工作。 e.target.value 是按钮中的undefined,在执行undefined + 1 时,您将收到NaN

我相信您想从状态中检索id。这将使您的功能像这样:

btnClick(e) {
  const { id } = this.state;
  this.setState({
       id: id+1
    },
    () => this.getData()
  )
}

或者您可能希望从当前状态派生您的 setState 调用,就像这样(我还删除了不需要的箭头函数声明):

btnClick(e) {
  this.setState(({ id }) => ({
       id: id+1
    }),
    this.getData
  )
}

最后,您可以对getData 函数进行完整性检查,以确保this.state.id 实际上是一个数字——您可以使用Number.isNaN()

【讨论】:

  • 感谢您的评论。我想在用户单击下一步时在第一页上显示 10 个条目,它将显示另外 10 个条目,前 10 个条目将被跳过。它可以通过环回分页。我做了手动工作,但我无法在反应中做到这一点
猜你喜欢
  • 2021-03-17
  • 2018-08-09
  • 1970-01-01
  • 2020-12-01
  • 2020-07-30
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
相关资源
最近更新 更多