我正在使用 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' ))
最佳答案
您的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()
.
关于javascript - react : Uncaught (in promise) Error: Request failed with status code 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55130756/