【问题标题】:How can I get localStorage to work with ReactJS?如何让 localStorage 与 ReactJS 一起工作?
【发布时间】:2022-01-04 01:42:31
【问题描述】:

我正在开发基于 MERN 的 Web 应用程序,但在让 ReactJS 将用户令牌保存到本地存储时遇到问题。它正确地向 MongoDB 发送数据并从 React UI 中取回令牌,但没有保存令牌。

这是形式:(我也在使用tailwind进行造型)

<form onSubmit={this.submitInfo} className="shadow-md rounded px-8 pt-6 pb-8 mb-4">
                                <div className="mb-4">
                                    <label className="block text-gray-700 text-sm font-bold mb-2">
                                        Username: 
                                        <input id="username" type="text" value={this.state.name} onChange={this.inputChange} className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"/>
                                    </label>
                                </div>

                                <div className="mb-4">
                                    <label className="block text-gray-700 text-sm font-bold mb-2">
                                        Email: 
                                        <input id="email" className="shadow" type="email" value={this.state.email} onChange={this.inputChange} className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"/>
                                    </label>
                                </div>

                                <div className="mb-4">
                                    <label className="block text-gray-700 text-sm font-bold mb-2">
                                        Password: 
                                        <input id="password" type="password" value={this.state.password} onChange={this.inputChange} className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"/>
                                    </label>
                                </div>
                                <div className="flex items-center justify-between">
                                    <input className="bg-primary hover:bg-highlight text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="submit" value="Signup"/>
                                </div>
                            </form>

这是单击提交按钮时运行的函数:

submitInfo(event){
        fetch(`http://localhost:5000/users/register`, {
            method: 'POST',
            headers: {
                'Content-type': 'application/json',
            },
            body: JSON.stringify({"userName":this.state.name, "email":this.state.email, "password":this.state.password})
        })
            .then(response => localStorage.setItem("token", JSON.stringify(response)))
            .catch(err => console.error(err));

        window.location.href = "/browse"
    }

我看不出我的实现有什么本质上的错误。我已经用邮递员测试了 API,它发回了一个非常好的令牌,所以问题必须在反应方面。有什么我忽略的吗?

编辑: 我尝试删除窗口重定向,但仍然无法保存令牌。

【问题讨论】:

  • 重定向将在 fetch 完成之前发生。您也没有阻止默认的表单提交过程
  • fetch 得到响应之前尝试event.preventDefault(); 看看页面是否正在重定向。

标签: javascript html reactjs local-storage


【解决方案1】:

除了cmets 所说的redirect 和preventDefault,您还需要先从响应对象中提取JSON 对象,然后再将其保存到localStorage。您可以通过以下方式完成所有这些操作:

submitInfo(event) {
  event.preventDefault();
  fetch(`http://localhost:5000/users/register`, {
    method: 'POST',
    headers: {
      'Content-type': 'application/json',
    },
    body: JSON.stringify({"userName":this.state.name, "email":this.state.email, "password":this.state.password})
  })
    .then(response => response.json())
    .then(data => {
      localStorage.setItem("token", JSON.stringify(data));
      window.location.href = "/browse";
    )
    .catch(err => console.error(err));
}

您可以在此处阅读有关使用 MDN 文档的fetch API 的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-30
    • 2017-06-11
    • 2023-02-02
    • 2020-03-31
    • 2017-06-25
    • 2020-12-13
    • 2012-02-02
    • 2011-02-22
    相关资源
    最近更新 更多