javascript - 同时执行两个方法
问题描述
目标:
当您按下“回家!”按钮时 您应该执行代码“fetch( https://jsonplaceholder.typicode.com/users
)”,然后被推送到“/home”
问题:
如何应用按钮可以同时执行提取和推送?
信息:
*我是 React JS 的新手
Stackblitz:
https ://stackblitz.com/edit/react-router-history-push-yux12z?file=components/User.js
import React from "react";
export class User extends React.Component {
fetchUsers() {
fetch(`https://jsonplaceholder.typicode.com/users`)
.then(response => response.json())
.then(data =>
this.setState({
users: data,
isLoading: false
})
)
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
return (
<div>
<h3>THE USER PAGE</h3>
<p>USER ID: {this.props.match.params.id}</p>
<button
onClick={() => {
this.props.history.push("/home");
}}
>
GO HOME!
</button>
</div>
);
}
}
解决方案
setSate 函数接受另一个可选输入,即在状态更新后执行的函数。
import React from "react";
export class User extends React.Component {
fetchUsers() {
fetch(`https://jsonplaceholder.typicode.com/users`)
.then(response => response.json())
.then(data =>
this.setState({
users: data,
isLoading: false
}, () => {
// this will be executed after the state was updated
// the data was fetched and the state was update
this.props.history.push("/home")
})
)
.catch(error => this.setState({ error, isLoading: false }, ()=>{
// the state was updated, you can redirect to home or an error page
this.props.history.push("/home")
}));
}
render() {
return (
<div>
<h3>THE USER PAGE</h3>
<p>USER ID: {this.props.match.params.id}</p>
<button
onClick={this.fetchUsers.bind(this)}
>
GO HOME!
</button>
</div>
);
}
}
推荐阅读
- node.js - 无法读取 VueJs 应用程序中未定义的属性“价格”
- git - 如何从父分支变基?
- azure - azure 集成帐户是否支持 HIPAA 版本 5010?
- c# - 如何正确选择自定义表格
- spring-mvc - 休眠形成查询错误以进行插入
- docker - 使用 docker 服务将滚动更新应用于 tensorflow 服务模型
- python - 删除多值列
- javascript - 从 vue 中声明的组件中获取数据
- java - Selenium:为三种环境运行具有不同 URL 的自动化代码
- c# - 有没有办法在 ASP.NET Core 3.0 API 中将属性名称更改为 snake_case?