React调用setState更新页码后发起API请求仍使用count旧值问题
问题原因
React 中setState是异步批量执行的,你在翻页函数中调用setState修改页码后立即发起请求,此时this.state.count还未完成更新,因此请求携带的仍是修改前的旧页码。
修复方案
方案1:使用setState回调(推荐)
setState支持传入第二个参数作为状态更新完成后的回调函数,我们将接口请求放到回调中执行,就能拿到最新的页码值。
只需修改handlePrev和handleNext函数即可:
handlePrev = () => { if (this.state.count > 1) { this.setState((prevState) => ({ count: prevState.count - 1 }), () => { // 状态更新完成后再调用接口 this.handleApi(); }) } }; handleNext = () => { if (this.state.count < this.state.data.total) { this.setState((prevState) => ({ count: prevState.count + 1 }), () => { this.handleApi(); }) } };
方案2:直接传递新页码参数
你也可以计算出新页码后,直接作为参数传给接口请求函数,无需等待状态更新完成:
// 改造接口请求函数,支持接收页码参数 handleApi = (targetPage = this.state.count) => { fetch(`http://localhost:9000/accounts?page=${targetPage}`) .then((res) => res.json()) .then((res) => { this.setState({ data: res }); }) .catch((err) => console.log(err)); }; handlePrev = () => { if (this.state.count > 1) { const newCount = this.state.count - 1; this.setState({ count: newCount }) // 直接传新页码发起请求 this.handleApi(newCount); } }; handleNext = () => { if (this.state.count < this.state.data.total) { const newCount = this.state.count + 1; this.setState({ count: newCount }) this.handleApi(newCount); } };
内容的提问来源于stack exchange,提问作者codework
相关产品推荐
相关产品推荐

