重复操作时,我可以使用哪种方法来更新状态?

时间:2019-08-19 08:16:05

标签: reactjs redux react-redux

我需要使用本地存储中的更新数据,但是通过这种方法,状态不会被更新而是被补充。有哪些替代方案?

export const contactList = [];

export function getContacts(state = contactList, action) {
  switch (action.type) {
    case 'LOAD_CONTACTS_FROM_STORAGE':
      for (let i = 0; i < localStorage.length - 1; i++) {
        state.push(JSON.parse(localStorage.getItem(`contact${i}`)))
      }
      let newState = [];
      newState = state;
      console.log(newState);

      return [...state];
    default:
      return state;
  }
}

1 个答案:

答案 0 :(得分:0)

请勿直接更改状态。如果要添加新的存储项到状态,只需将它们保存到新阵列并将其添加到状态。如果要用存储项目替换状态,请返回存储项目数组。

export const contactList = [];

export function getContacts(state = contactList, action) {
  switch (action.type) {
    case 'LOAD_CONTACTS_FROM_STORAGE':
      let storageItems = [];
      for (let i = 0; i < localStorage.length - 1; i++) {
        storageItems.push(JSON.parse(localStorage.getItem(`contact${i}`)))
      }
      return [...state, ...storageItems];  // Or return storageItems; if you want to replace the state
    default:
      return state;
  }
}