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

使用Next.js访问/counter/counter-state出现404错误,请求排查

问题原因及解决办法

1. 路由匹配错误(404核心原因)

Next.js Pages Router(传统路由模式)的路由规则是文件路径直接对应访问路径:

  • 要访问localhost:3030/counter/counter-state,你的项目目录结构必须满足:
    pages/
      counter/
        counter-state.js  # 也可以创建 counter-state/index.js
    

如果counter-state.js未放在pages/counter目录下,或者目录层级不符,就会触发404错误。

2. 代码中的其他问题(路由修复后仍会导致功能异常)

  • 组件名拼写错误:UpdateCOunterButton应为UpdateCounterButton(字母O和U顺序错误),会导致组件无法识别,引发渲染失败。
  • onClick事件触发时机错误:按钮的onClick直接调用props.updateCount(value=>value+1),会在组件渲染时立即执行更新逻辑,造成无限循环。正确写法是传递一个函数:
    <button onClick={() => props.updateCount(value=>value+1)}>+1</button>
    

修正后的完整代码:

import { useState } from "react";

function UpdateCounterButton(props){
    return <div>
        <button onClick={() => props.updateCount(value => value + 1)}>+1</button>
    </div>
}

function CounterRender(props){
    return <div>{props.count}</div>
}

export default function CounterState(){
    const [counter, setCounter] = useState(0)
    return(
        <>
            <CounterRender count={counter} />
            <UpdateCounterButton updateCount={setCounter}/>
        </>
    )
}

内容的提问来源于stack exchange,提问作者Pravin Poudel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:02:16