reactjs - React 功能组件中的依赖 api 调用
问题描述
所以我有一个功能组件,它通过 API 调用来获取“播放器”json 对象。在那个获取的“玩家”对象中,我有一个嵌套的“团队”json 对象,其中包含我需要在单独的 API 调用中使用的 id。由于 API 调用的性质是异步的,我如何保证第二个 API 调用能够正常工作。
const [player, setPlayer] = useState({});
async function fetchPlayer() {
const res = await fetch(baseUrl + "/Players/" + player_id);
res
.json()
.then(res => setPlayer(res));
}
useEffect(() => {
fetchPlayer();
}, []);
const {
firstname = " ",
lastname = " ",
team
} = player;
const {
name = " ",
team_id = 0
} = team || {};
// what I want to do. Team_id isn't set however...
const [thing, SetThing] = useState({});
async function fetchThing() {
const res = await fetch(baseUrl + "/Thing/" + team_id);
res
.json()
.then(res => setThing(res));
}
基本上我已经能够获取团队 json 对象并且它是 team_id 但我不确定如何实现另一个依赖于团队 ID 的 API 调用。
我尝试添加另一个异步函数来容纳第二个 API 调用,但在该调用中,team_id 尚未由第一个 API 调用设置。任何想法都会很棒,谢谢!
解决方案
发现您可以为“听”的第二个参数添加值。对该值的更改将调用它所绑定的 useEffect。例如我添加了这个:
const [thing, setThing] = useState({});
async function fetchThing() {
const res = await fetch(baseUrl + "/Thing/" + team_id);
res
.json()
.then(res => setThing(res));
}
useEffect(() => {
fetchThing();
}, [team_id]);
所以现在上面的 useEffect 会在 team_id 改变时触发。因此可以保证 team_id 已设置,然后 useEffect 使用我们在第一次 API 调用中等待的新 team_id 调用 fetch。
推荐阅读
- html - 在其他 div 之上分层 div
- mongodb - 如何将mongodb日志发送到kafka?
- couchdb - Hyperledger Fabric CouchDB 索引:“找不到匹配的索引”
- c# - 在池中配置单个 IdentityServer4 以实现高可用性
- mysql - SQL如何将相同数据值的总和相加
- reactjs - 如何使用 axios 在 React Native 中获取数据
- ms-access - IIS 上的经典 ASP 网络故障转移
- ruby-on-rails - 使用“Active Storage”Ruby on Rails 验证正确的图像类型
- flutter - 未处理的异常:MissingPluginException(在通道 plugins.flutter.io/share 上找不到方法共享的实现)
- spring - 由于嵌入式 Elasticsearch,测试执行会持续很长时间