【问题标题】:How to make a second API call based on the first response?如何根据第一个响应进行第二个 API 调用?
【发布时间】:2019-12-14 00:32:03
【问题描述】:

我需要调用 2 个 API 来在我的组件上显示数据,但第二个 api 需要来自第一个 API 响应的标头。 我正在使用 React Hooks。我从第一个响应中更新了状态,以便稍后可以在第二次调用中使用它,但它未定义。我做错了什么?

P.s 一种更好的调用方式(可能使用 async/await)会很受欢迎

 const [casesHeaderFields, setCasesHeaderFields] = useState([]);
 const [casesFields, setCasesFields] = useState([]);

  useEffect(() => {
    const fetchData = () => {
      const result1 = axios
        .get(`firstUrl`)
        .then(response => {
         //I need this as headers for my second API
          setCasesHeaderFields(
            response.data.result.fields
          );
        });

      const result2 = axios
        .get(`url${casesHeaderFields} //here i want to pass params from 
         //first response)
        .then(response => {
          setCasesFields(response.data.result.record_set);
        });
    };
    fetchData();
  }, []);

【问题讨论】:

  • 链接您的承诺或使用async/await 并阻止执行您的result2 调用。 P.s a better way of doing this calls (maybe using async/await) would be much appriciated 是什么意思? async/ await 很简单……

标签: javascript reactjs axios


【解决方案1】:

查询result1 和result2 看起来是连续的,但同时存在。换句话说,result2 不会等到result1 完成后才被执行。

这是一个使用 async/await 链接承诺的工作示例:

useEffect(async () => {
  try {
    // Make a first request
    const result1 = await axios.get(`firstUrl`);
    setCasesHeaderFields(result1.data.result.fields);

    // Use resutlt in the second request
    const result2 = await axios.get(`url${"some params from result1"}`);
    setCasesFields(result2.data.result.record_set);
  } catch (e) {
    // Handle error here
  }
}, []);

编辑

基于 cmets,这是使用 async with useEffect 的最佳方法,而不会在控制台中发出警告:

useEffect(() => {
  const fetchData = async () => {
    try {
      // Make a first request
      const result1 = await axios.get(`firstUrl`);
      setCasesHeaderFields(result1.data.result.fields);

      // Use resutlt in the second request
      const result2 = await axios.get(`url${casesHeaderFields}`);
      setCasesFields(result2.data.result.record_set);
    } catch (e) {
      // Handle error here
    }
  };

  fetchData();
}, []);

【讨论】:

  • axios.get(url${"some params from result1"})?例如像 result1.data.fields?还是我通过状态 caseHeaderFields?
【解决方案2】:

您可以使用async/await 来缓解混乱。

useEffect(async () => {
    const response = await axios.get(`firstUrl`)
    const result = await axios.get(`url${response.data.result.fields}`)
    console.log(result.data)
})

【讨论】:

  • 你不能调用useEffect函数async。如果你这样做,至少 React 会发出警告。
【解决方案3】:

你可以这样写:

  useEffect(() => {
      return axios
        .get(`firstUrl`)
        .then(response => {
          return response.data.result.field
        }).then(result => { 
         return axios.get(`url${result}`)
        });
   });

使用异步/等待:

  useEffect(async () => {
      const result1 = await axios
        .get(`firstUrl`)
        .then(response => {
          return response.data.result.field
        });
      const result2 = await axios.get(`url${result1}`)
      return result2 
   });

【讨论】:

  • 您可以注意到箭头功能不需要使用return,只需写例如=> response.data.result.field。
  • 将async 与 useEffect() 一起使用的方法不正确
  • 为什么我没有用 try-catch 块包装我的代码?
  • 不,看看edit Baboo answer made for same issue这是正确的方法
【解决方案4】:

在 .then 中进行第二次调用,然后链接到第一个承诺链的末尾......简单来说,链接你的承诺

类似

useEffect(() => axios.get(`firstUrl`)
    .then(response => {
        setCasesHeaderFields(response.data.result.fields);
        return response.data.result.fields;
    })
    .then(casesHeaderFields => axios.get(`url${casesHeaderFields}`))
    .then(response => {
        setCasesFields(response.data.result.record_set);
    }), []);

【讨论】:

  • 对不起,这不是很紧...括号失败:p
  • 现已修复 - 对此感到抱歉
  • 谢谢。我选择这个作为答案,因为你已经为我准备好了:p 干杯
  • 是的,我想你仍然想做setCasesHeaderFields 和setCasesFields 的东西(尽管我不知道它在做什么:p)
【解决方案5】:

您可以将结果链接起来,因为它们是常规的承诺: Ref

axios.get(...)
  .then((response) => {
    return axios.get(...); // using response.data
  })
  .then((response) => {
    console.log('Response', response);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-03
    • 2019-11-30
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2022-01-22
    相关资源
    最近更新 更多