You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中onClick访问getServerSideProps获取id的方法

错误原因

你的写法有3个核心问题:

  • getServerSideProps 是Next.js中仅在服务端执行的函数,代码运行在Node.js环境,和你浏览器端的React组件完全隔离,根本访问不到组件内通过useState定义的setid方法,在这里调用setState不会有任何效果。
  • 你在getServerSideProps的返回值里没有把id1放到props对象中,组件根本接收不到这个参数。
  • ctx.query拿到的是所有路由参数组成的对象,直接把整个对象拼接到接口请求URL里会得到[object Object],应该取具体的参数字段,比如动态路由文件名为[id].js时,参数值是ctx.query.id。
正确实现

不需要额外用useState中转,直接把id1通过props传给组件即可,组件内的事件函数可以直接访问props上的值:

// 组件部分:从props解构拿到服务端返回的id
function Query({ posts, answerPosts, id }) {
  function clickQuestion() {
    console.log(id) // 这里可以正常获取到服务端传递的id值
  }

  return (
    <div>
      {/* 你的页面业务内容 */}
      <button onClick={clickQuestion}>点击获取id</button>
    </div>
  )
}

// getServerSideProps部分
export async function getServerSideProps(ctx) {
  // 替换成你实际的路由参数名
  const id1 = ctx.query.id

  const queryRequest = fetch(`https://askover.wixten.com/questone/${id1}`).then(res => res.json())
  const answerRequest = fetch(`https://askover.wixten.com/answersapi/${id1}`).then(res => res.json())

  const [posts, answerPosts] = await Promise.all([queryRequest, answerRequest])

  return {
    props: {
      posts,
      answerPosts,
      id: id1 // 把id加入返回的props,传递给组件
    }
  }
}

export default Query

如果你后续有修改id的需求,必须把id存在state里,也不要在服务端调用setState,应该用props初始化state,必要时加effect同步:

function Query({ posts, answerPosts, id: propsId }) {
  const [id, setid] = useState(propsId)

  // 如果props里的id可能发生变化,加这段同步逻辑
  useEffect(() => {
    setid(propsId)
  }, [propsId])

  function clickQuestion() {
    console.log(id)
  }

  // 其余渲染逻辑不变
}

内容的提问来源于stack exchange,提问作者vivek kn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 18:21:52