如何改变API调用时,下拉值改变nextjs



我正在做一个nextjs项目,这是一个日历。当国家和年份改变时,日历应该改变,我使用假期API。API url包含国家和年份参数(https://localhost:5001//holiday?&country=${country}&year=${year})。所以我需要传递国家和年份,在Holiday.tsx中,我使用下拉选择国家和年份。

我在获取数据时遇到了困难。我如何将这些选定的国家和年份值传递给index.tsx。我不使用动态路径。我只有index.ts.

api.ts

import axios from "axios";
import { GetAllHolidaysData } from "../interfaces/GetAllHolidaysData";  
process.env.NODE_TLS_REJECT_UNAUTHORIZED;
const http = axios.create({ baseURL: process.env.NEXT_PUBLIC_API });
export const GetAllHolidays = (country: string, year: number) => {
console.log(country, year);
return http.get<GetAllHolidaysData>(
`/holiday?&country=${country}&year=${year}`
);
}; 

index.tsx

const Home: NextPage<{ holidays: GetAllHolidaysData }> = ({ holidays }) => {
return (
<>
<Holidays holidays={holidays}/>
</>
);
};
export const getServerSideProps: GetServerSideProps = async () => {
// let country = "ro";
// let year = "2021";
let holidays: GetAllHolidaysData;
try {
const { data } = await GetAllHolidays(country, year);    // I struggled at this line how to bind country and year those are selected in Holiday.tsx file using a dropdwon
holidays = data;
} catch (error) {
console.log(error);
}
return {
props: {
holidays,
},
};
};
export default Home;

假期。TSX -国家和年份变化在这里

const Holidays: NextPage<data> = ({ holidays }) => {
const [selectedYear, setselectedYear] = useState(currentYear);
const [selectedCountry, setselectedCountry] = useState(countries[169]);
const countryChangeHanlder = (e) => {
GetAllHolidays(e.value, year);
// setCountry(e.label);
setselectedCountry(e);
console.log(selectedCountry);
};
const yearChangeHanlder = (e) => {
const countryCode = Object.entries(selectedCountry)[0].map((i) => i)[1];  
GetAllHolidays(String(countryCode), e.value);
setYear(e.value);
setselectedYear(e);

};
}

简短回答:

你不能用getServerSideProps使用从下拉选择,考虑到下拉页面上你想要使用这个getServerSideProps返回。相反,您应该在组件本身(const Home: NextPageHoliday.tsx)中执行此操作。

解释:

getServerSideProps之前在服务器上被称为页面返回给客户端。您可以在这里查看。

您的下拉选择是可用的页面返回(并呈现)之后,因此您可以访问这些值,因此您可以使用选择

发出请求更新:

你可以这样做:

const Holidays: NextPage<data> = ({ holidays }) => {
const [selectedYear, setselectedYear] = useState(currentYear);
const [selectedCountry, setselectedCountry] = useState(countries[169]);
useEffect(() => {
(async () => {
try {
const { data } = await GetAllHolidays(country, selectedYear);
// use your data from here
} catch (error) {
console.log(error);
})()
}, [selectedYear])
const countryChangeHanlder = (e) => {
GetAllHolidays(e.value, year);
// setCountry(e.label);
setselectedCountry(e);
console.log(selectedCountry);
};
const yearChangeHanlder = (e) => {
const countryCode = Object.entries(selectedCountry)[0].map((i) => i)[1];  
GetAllHolidays(String(countryCode), e.value);
setYear(e.value);
setselectedYear(e);

};
}

相关内容

  • 没有找到相关文章

最新更新