我是 React js 的新手,并且一直在构建一些工作得非常好的东西。但到目前为止,要进行的 api 调用是在各自的组件内定义的。因此,如果要对 IP 或端点进行任何更改,我需要在每个地方进行更改。如何将所有 api 调用分离到一个文件中,并在相应的组件文件中对结果执行操作。
下面是一个例子:
import axios from "axios";
function get_all_user(){
axios({
method: "get",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
url: "http://127.0.0.1:8000/app/users/",
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
})
}
function get_single_user(userid){
axios({
method: "get",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
url: "http://127.0.0.1:8000/app/users/"+userid,
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
})
}
Run Code Online (Sandbox Code Playgroud)
在每个组件中我都需要进行 api 调用。所有这些 api 调用都需要位于一处。任何帮助表示赞赏。
我有一个数组。我想在其中迭代并进行条件检查并显示正确的元素。我正在使用功能组件。
下面是一个例子:
import React, { useState, useEffect } from "react";
function Job(props) {
const [resp_data, setdata] = useState("");
const [look, setlook] = useState("");
useEffect(() => {
// some api calls happen here and response data is stored in state resp_data
}, [props]);
return (
<>
<div className="product_list">
{resp_data.length > 0
? resp_data.map((item) => {
{item.looking_for === "work" ? (
<div className="card-rows work" key={item.id}>
work
</div>
) : (<div className="card-rows no_work" key={item.id}>
No work
</div>)
}
})
: <div>array length is …Run Code Online (Sandbox Code Playgroud)