我在React中有一个视图,它有两个useEffect,一个用于排序列表,另一个用于获取列表。 当 dataTailors 有值时,“isLoading”允许查看所有列表。
export const ClientMainPage = () => {
const [dataTailors, setDataTailors] = useState([]);
const [sortItemSelected, setSortItemSelected] = useState("none");
const [isfetch, setIsfetch] = useState(false);
useEffect( () => {
setIsfetch(true);
let uFetchAux = new uFetch();
uFetchAux.getAllTailors().then (res => setDataTailors(res));
console.log(dataTailors);
},[]);
useEffect(() => {
const sortByNameItems = (itemSeleted) => {
const options = {
asc: [...dataTailors].sort((a, b) => (a.name < b.name ? -1 : 1)),
desc: [...dataTailors].sort((a, b) => (a.name < b.name ? 1 : -1)),
none: [...dataTailors]
};
return options[itemSeleted];
};
setDataTailors(sortByNameItems(sortItemSelected));
}, [sortItemSelected]);
return (
<div className="MainPage">
{isfetch?( <div>
<NavBar title="Cliente">
<SortBy sortItems={(items) => setSortItemSelected(items)}></SortBy>
</NavBar>
<ClientTable tailors={dataTailors}></ClientTable></div>)
:<div>{setIsfetch(false)}</div>
}
</div>
);
};
这是调用我的服务的多个接口,它位于“http://localhost:8088”中。
import axios from "axios";
class uFetch {
async getAllTailors() {
const http = axios.create({
baseURL: "http://localhost:8088",
headers: {
"Content-type": "application/json"
},
responseType: "json",
mode: "cors",
});
return await http.get("/tailor")
.then( resp => {console.log(resp.data); return resp.data })
.catch(e => {console.log(e); });;
}
}
export default uFetch;
当我执行这段代码时。 useEffects 不执行
useEffects 执行,并获取列表
我找到了解决方案
export const ClientMainPage = () => {
const [dataTailors, setDataTailors] = useState([]);
const [sortItemSelected, setSortItemSelected] = useState("none");
useEffect( () => {
getAllTailors().then(d=> {console.log( "call inside " +d); setDataTailors(d) });
console.log( "useEffect " +dataTailors);
},[]);
useEffect(() => {
const sortByNameItems = (itemSeleted) => {
const options = {
asc: [...dataTailors].sort((a, b) => (a.name < b.name ? -1 : 1)),
desc: [...dataTailors].sort((a, b) => (a.name < b.name ? 1 : -1)),
none: [...dataTailors]
};
return options[itemSeleted];
};
setDataTailors(sortByNameItems(sortItemSelected));
}, [sortItemSelected]);
if (!dataTailors) return null;
return (
<div className="MainPage">
<div>
<NavBar title="Cliente">
<SortBy sortItems={(items) => setSortItemSelected(items)}></SortBy>
</NavBar>
<ClientTable tailors={dataTailors}></ClientTable></div>
</div>
);
};
和
import axios from "axios";
export const getAllTailors = async () => {
const http = axios.create({
baseURL: "http://localhost:8088",
headers: {
"Content-type": "application/json"
},
responseType: "json",
mode: "cors",
});
return await http.get("/tailor")
.then( (resp) => {console.log("getAllTailors " + resp.data); return resp.data })
.catch(e => {console.log(e); });
}