Nak*_*iya 5 reactjs server-side-rendering next.js
我想传递此函数中的参数,以便在应用某些过滤器时在同一页面上获取更新/过滤的数据?
这对于初始渲染工作正常,但我无法从同一组件获取更新的数据,因为该 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,
    },
  }
}
您无法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>)}
    )
}
| 归档时间: | 
 | 
| 查看次数: | 1146 次 | 
| 最近记录: |