3 回答

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

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);
}
);
};

TA貢獻1852條經驗 獲得超1個贊
所以我簡單地通過在構造函數中設置狀態而不是在組件 didMount 上設置狀態來解決我的問題,但我不知道為什么當它的代碼完全相同時它會起作用?
constructor(props) {
super(props);
this.state = {
healthData: (JSON.parse(localStorage.getItem('user_data')))
}
}
- 3 回答
- 0 關注
- 185 瀏覽
添加回答
舉報