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

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

componentDidUpdate 中的先前狀態和當前狀態相同

componentDidUpdate 中的先前狀態和當前狀態相同

慕絲7291255 2021-06-29 01:20:05
在每個模塊的儀表板中,其布局數據(使用 react-grid-layout)與模塊數據分開存儲,并且每個模塊數據都存儲在數據庫中。當前模塊數據和布局數據存儲在 Dashboard 組件狀態中。componentDidMount()每當模塊或布局的先前狀態與當前狀態不同時,我試圖在內部調用單獨的 axios POST 請求,以保存數據庫中的更改。但是通過調試和日志記錄,我看到prevState等于this.state.以下是改變相關狀態的componentDidMount()方法和方法:componentDidUpdate(prevProps, prevState) {// JSON.stringify comparison for proof of concept since the order does not change        if(JSON.stringify(prevState.modules) !== JSON.stringify(this.state.modules))            API.post('Adminusers/StoreUserModuleData', "module_data=" + JSON.stringify(this.state.modules))                        .then((res) => console.log(res))                        .catch(err => {throw new Error(err)});        if(JSON.stringify(prevState.layouts) !== JSON.stringify(this.state.layouts))            API.post('Adminusers/StoreAdminUserLayouts', "layouts=" + JSON.stringify(this.state.layouts))                        .then((res) => console.log(res))                        .catch(err => {throw new Error(err)});      }addNewModuleInLayout(moduleData) {        let newLayout = this.state.layouts;        let newModule = this.state.modules;        for (let key in newLayout) {            if (newLayout.hasOwnProperty(key)) {                newLayout[key].push({                    i: moduleData.type,                    x: (newLayout[key].length * 1) % 3,                    y: Infinity,                    w: 1,                    h: 5                });某個模塊的模塊數據和布局數據的示例如下:// layouts{ "md": [{ i: "current-user", x: 0, y: 0, w: 3, h: 5, isDraggable: false, isResizable: true }], "lg": [{ i: "current-user", x: 0, y: 0, w: 3, h: 5, isDraggable: false, isResizable: true }], "sm": [{ i: "current-user", x: 0, y: 0, w: 3, h: 5, isDraggable: false, isResizable: true }], "xs": [{ i: "current-user", x: 0, y: 0, w: 3, h: 5, isDraggable: false, isResizable: true }]}// module data[{ type: "current-user", content: " ", title: "Current User Module" }]任何人都可以指導我在這里做錯了什么,這兩個州都是平等的嗎?
查看完整描述

1 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

嘗試在這兩個更新您的數組聲明addNewModuleInLayout,并removeModule以


const newLayout = { ...this.state.layouts }; // from let newLayout = this.state.layouts

const newModule = [...this.state.modules]; // from let newModule = this.state.modules

在 cDM 中,您不會在狀態上創建模塊/布局數組的“新”副本,而是直接引用數組。當你更新數組時,你實際上改變了你的狀態,所以當你prevState與this.state字符串化版本進行差異時是相等的。


這不會深入復制您的布局對象,因此在推送到布局數組時您會遇到同樣的問題。您可以通過在更新布局而不是推送時創建新數組來解決此問題


newLayout[key] = [

 ...newLayout[key], 

 {

   i: moduleData.type,

   x: (newLayout[key].length * 1) % 3,

   y: Infinity,

   w: 1,

   h: 5

 }

]; // from newLayout[key].push({DATA}); in addNewModuleInLayout

因為你用filter在removeModule你那里應該很好


查看完整回答
反對 回復 2021-07-01
  • 1 回答
  • 0 關注
  • 384 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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