Pix*_*lik 6 reactjs next.js stenciljs
我正在尝试让我的自定义表单域与 NextJS 很好地配合。但水分似乎有问题。
这是我的网络组件:
@Component({
tag: 'test-checkbox',
shadow: false,
})
export class TestCheckbox {
@Prop() name: string;
@Prop() value: boolean;
@Prop() label: string;
@Prop() innerValue: string;
render() {
const { value, name } = this;
return (
<div>
<label htmlFor={this.name}>{this.label}</label>
<input type="checkbox" name={name} id={name} checked={!!value} />
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 Stencil ReactJS 包装器,因此 NextJS 中的代码将如下所示:
const Form = () => {
const formRef = useRef();
const handleInput = (e) => {
///
};
const handleSubmit = (e) => {
///
};
return (
<form ref={formRef} onSubmit={handleSubmit}>
<TestInput name='damn' label='labeltest' onInput={handleInput} />
<button type='submit'>submit</button>
</form>
);
};
export default Form;
Run Code Online (Sandbox Code Playgroud)
当我在 nextJS 应用程序中运行此组件时,我将收到以下错误:
Unhandled Runtime Error
Error: Hydration failed because the initial UI does not match what was rendered on the server.
Run Code Online (Sandbox Code Playgroud)
当我在 Web 组件中将 Shadow 设置为 true 时,我没有收到错误,但现在提交时表单字段不会显示在我的 FormData 中。
我猜测水合问题是因为模板组件会过早或过晚地渲染其组件内部,因此服务器上的内容与客户端上的内容不同。
有没有办法抑制通知(它在生产中不存在,除了消息之外,一切似乎都工作正常)或者有没有办法及时加载模板文件,以便服务器和客户端有正确的数据来启动保湿?
小智 0
我找到了解决这个问题的方法,那就是禁用 Next.js 的服务器端渲染。要将其应用到您的案例中,当您导入表单组件时,而不是
import Form from './form'
const Page = () => (
<>
<Form />
</>
)
Run Code Online (Sandbox Code Playgroud)
你应该使用动态导入
import dynamic from 'next/dynamic'
const FormWithoutSSR = dynamic(() => import('./form'), {
ssr: false
})
const Page = () => (
<>
<FormWithoutSSR />
</>
)
Run Code Online (Sandbox Code Playgroud)
您在https://javascript.plainenglish.io/how-to-solve-Hydration-error-in-next-js-a50ec54bfc02中有不同的方法
| 归档时间: |
|
| 查看次数: |
1405 次 |
| 最近记录: |