Is there a way to use useState in Next.js server-side rendering?
P粉245489391
P粉245489391 2024-02-17 20:08:27
0
1
377

I want to get a value from the client side and use it on the server side,

But I don't know how to use useState, and I know there is no way to use useState on the server side So is there any other solution that can be used instead? ! Actually, there is a url on the server side and I want to get the value from the client and use ${} in that url.

P粉245489391
P粉245489391

reply all(1)
P粉481366803

You can achieve your goal by passing client-side values ​​to the server via requests, query parameters, or API endpoints.

Client:

import { useState } from 'react';

const MyComponent = () => {
  const [myValue, setMyValue] = useState('');

  const handleSubmit = () => {
    fetch(`/api/myEndpoint?value=${encodeURIComponent(myValue)}`)
      .then((response) => response.json())
      .then((data) => {
        // 如果需要,可以对从服务器返回的数据进行处理
        console.log(data);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  };

  return (
    <div>
      <input value={myValue} onChange={(e) => setMyValue(e.target.value)} />
      <button onClick={handleSubmit}>提交</button>
    </div>
  );
};

Service-Terminal:

export default function handler(req, res) {
  const { value } = req.query;

  // 使用从客户端接收到的'value'

  res.status(200).json({ message: `接收到的值:${value}` });
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template