如何用更新的接口url从同一组件中调用getServerSideProps? [英] How to recall getServerSideProps from same component with updated api url?

查看:17
本文介绍了如何用更新的接口url从同一组件中调用getServerSideProps?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要传递此函数中的参数,以便在应用某些筛选器时将更新/筛选的数据放在同一页上?

这对于初始呈现工作正常,但我无法从同一组件获取更新数据,因为此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,
    },
  }
}

推荐答案

您不能从客户端组件调用getServerSidePropsgetServerSideProps只能在服务器上运行。相反,每当需要筛选数据时,您都希望直接从客户端发出请求。

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>)}
    )
}

这篇关于如何用更新的接口url从同一组件中调用getServerSideProps?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆