如何召回getServerSideProps从相同的组件更新api url?



我想在这个函数中传递参数,以便在应用一些过滤器时在同一页面上获得更新/过滤的数据?

这是工作良好的初始渲染,但我无法获得更新的数据从我的相同的组件,因为这个getServerSideProps函数是我的组件之外。

Mycomponent添加

let API_URL = `https://api.spaceXdata.com/v3/launches?limit=100`
const spacex = ({ missions }) => {
const [allMissions, setallMissions] = useState(missions)
const filterResults = (filter, value) => {
getServerSideProps(`${API_URL}&${filter}=${value}`) // but this is not accessible from here, getServerSideProps is undefined here as this is outside the function
}
render() {
return (
{missions.map((mission) => <li>mission.name</li>)}
)
}
export const getServerSideProps = async (API_URL) => {
const res = await fetch(API_URL)
const missions = await res.json()
if (!missions) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: {
missions,
},
}
}

您不能从客户端的组件调用getServerSideProps,getServerSideProps只能在服务器上运行。

相反,当你需要过滤数据时,你应该直接从客户端发出请求。

const API_URL = `https://api.spaceXdata.com/v3/launches?limit=100`
const SpaceX = ({ missions }) => {
const [allMissions, setAllMissions] = useState(missions)
const filterResults = async (filter, value) => {
const res = await fetch(`${API_URL}&${filter}=${value}`)
const missions = await res.json()
setAllMissions(missions)
}
return (
{allMissions.map((mission) => <li>mission.name</li>)}
)
}