使用 REACT 和 Node.js。
Node.js 连接并更新 JSON 文件。 当我从后端文件返回时,我不会返回到之前所在的位置。
相反,网页会完全刷新,所以我又回到了开头。
答案是创建 sessionStorage 来跟踪我在哪里吗?完全不知道该做什么。
我从 app.js 开始,并使用 useState() 来跟踪我想看到的页面视图。 {const [currentView, setCurrentView] = useState('home'); // 默认视图}
如您所见,默认值为“home”。稍后在代码中有一个“管理”按钮选项,可以将管理部分带入视图
{ <button onClick={() =>
setCurrentView('admin')} className="big-btn" aria-label="Go to Admin
Section">Admin</button>}
连接到这部分代码以显示Admin.js文件的内容
{{/* Admin View */}
<div className={`mainViewContainer ${currentView === 'admin' ? 'active' : ''}`}>
<div id="adminViewContainer">
<Admin backButton={
<button
onClick={() => setCurrentView('home')}
className="mainBackBtn"
aria-label="Go back to Home">← Back
</button>
}/>
</div>
</div>}
一切正常,可以看到管理屏幕,允许我将某些信息添加到输入字段中。点击提交按钮会获取我添加的信息,并将该数据作为“POST”事件发送到名为 server.js 的后端文件。
该 JSON 文件已从 server.js 正确更新。然而有趣的是之后发生的事情。我最初返回到 admin.js 脚本,因为我可以看到我的表更新了新信息。
然后我翻回最初的“主”屏幕。我可以看到这是一次彻底的刷新,因为我之前用于跟踪正在发生的情况的所有控制台日志都消失了。然后出现启动 app.js 时的初始控制台日志语句。
我可以通过删除与 server.js 的连接来解决问题,只需使用与更新输入字段关联的 useState() 来更新管理部分中的表。但 JSON 文件当然不会更新。
在此代码块中,在 admin.js 中,我调用了 server.js 文件,并且返回的“响应”文本始终确认成功。我必须将消息移植到本地存储,以便我可以确认成功(由于控制台日志在重新启动时被擦除)
{/*
Update information in the players.JSON file
'http://localhost:5000/serverURL' will either receive a POST or PUT
as depenedent on 'method' parameter
*/
const updateJsonFile = async (newData, method, action) => {
try {
const response = await fetch('http://localhost:5000/serverURL', {
method: method,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: action, // Include action in the request body
data: newData // The new player or update data
}),
});
if (!response.ok) {
console.log('Failed to update JSON file: ', response.statusText)
throw new Error('Failed to update JSON file: ', response.statusText);
}
const responseData = await response.json();
if (responseData.success) {
console.log(`SUCCESS: ${responseData.message}`, responseData);
logToLocalStorage(`Success in add server data ${responseData}`);
// Optionally provide UI feedback to the user, e.g., alert or notification
} else {
console.warn(`WARNING: Operation completed, but there may be issues:
${responseData.message}`);
logToLocalStorage(`FAILURE in add server data ${responseData}`);
}
// Consider providing user feedback here, e.g., alerting the user.
} catch (error) {
console.error('ERROR: updating JSON file:', error.message);
alert('Unable to update the JSON file. Please try again later.'); // Alert user about
the error
}
};}
非常感谢任何建议,我也感谢任何花时间阅读本文的人。
点击提交按钮即可获取信息..
某些浏览器事件具有与其关联的默认行为。例如,当单击其中的按钮时发生的提交事件将默认重新加载整个页面。请参阅下面的示例代码和测试运行观察。
应用程序.js
export default function Signup() {
return (
<form onSubmit={() => alert('Submitting!')}>
<input />
<button>Send</button>
</form>
);
}
试运行及观察:
点击提交按钮后,输入的文本将被清除。
您可以在事件对象上调用 e.preventDefault() 来阻止这种情况发生。下面的代码可以阻止它。
应用程序.js
export default function Signup() {
return (
<form
onSubmit={(e) => {
e.preventDefault();
alert('Submitting!');
}}
>
<input />
<button>Send</button>
</form>
);
}
试运行及观察:
点击提交按钮后,输入的文本将被保留。
您可以看到这里已经讨论了相同的内容:防止默认行为