我想在此函数中传递参数以在应用某些过滤器时在同一页面上获取更新/过滤的数据?
这对于初始渲染工作正常,但我无法从我的同一个组件中获取更新的数据,因为这个 getServerSideProps 函数在我的组件之外。
我的组件
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,
},
}
}
答案 0 :(得分:0)
您不能从客户端上的组件调用 getServerSideProps
,getServerSideProps
只能在服务器上运行。相反,您需要在需要过滤数据时直接从客户端发出请求。
let 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>)}
)
}