亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么在reactjs中使用JSON.parse會導致跨源錯誤?

為什么在reactjs中使用JSON.parse會導致跨源錯誤?

白豬掌柜的 2023-10-17 15:47:06
所以我有一個 JSON 數據數組保存到本地存儲,如下所示localStorage.setItem('user_data', JSON.stringify(data));像這樣從本地存儲獲取,但 console.log(this.state.healthData) 返回 null  constructor(props) {        super(props);        this.state = {            healthData: {}        }    } this.setState({ healthData: JSON.parse(localStorage.getItem('user_data')) });但我知道數據可以被提取,因為 console.log(localStorage.getItem('user_data'));打印了這個 {"age":"20","gender":"male","goal":"recomp","height":"181","weight":" 80”}。所以我也嘗試過,console.log(JSON.parse(this.state.healthData))但這會導致“跨源錯誤”事情是這段代碼在我的 app.js 頁面上運行,正如您可能在屏幕截圖日志中看到的那樣{age: "20", gender: "male", goal: "recomp", height: "181", weight: "80"}.那么是什么導致了這種情況,還有其他方法可以做到這一點嗎?
查看完整描述

3 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

每當 JSON.parse() 收到無效字符串時,React 就會拋出跨域錯誤,您應該能夠使用以下命令重新創建它JSON.parse('')。為什么 React 允許這種情況發生,我有自己的看法,但是您需要編寫一些可以 JSON.parse() 的內容,以便localStorage.getItem('user_data')您的代碼正常工作。您應該看到console.log(this.state.healthData)它不是有效的 JSON 字符串。



查看完整回答
反對 回復 2023-10-17
?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

我嘗試這樣做,效果很完美。


您必須確保狀態已更改。(通過回調/useEffect)


test = () => {

    const data = {

      age: "20",

      gender: "male",

      goal: "recomp",

      height: "181",

      weight: "80"

    };

    localStorage.setItem("user_data", JSON.stringify(data));

    this.setState(

      {

        healthData: JSON.parse(localStorage.getItem("user_data"))

      },

      () => {

        console.log(this.state.healthData);

      }

    );

  };


查看完整回答
反對 回復 2023-10-17
?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

所以我簡單地通過在構造函數中設置狀態而不是在組件 didMount 上設置狀態來解決我的問題,但我不知道為什么當它的代碼完全相同時它會起作用?


constructor(props) {

        super(props);

        this.state = {

            healthData: (JSON.parse(localStorage.getItem('user_data')))

        }

    } 


查看完整回答
反對 回復 2023-10-17
  • 3 回答
  • 0 關注
  • 185 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號