Reactjs React Hooks createContext:当它是一个数组时,如何更新UserContext?

Reactjs React Hooks createContext:当它是一个数组时,如何更新UserContext?,reactjs,react-hooks,context-api,Reactjs,React Hooks,Context Api,我的UserContext组件中有状态: var initialState = { avatar: '/static/uploads/profile-avatars/placeholder.jpg', markers: [] }; var UserContext = React.createContext(); function setLocalStorage(key, value) { try { window.localStorage.setItem(key, JSO

我的UserContext组件中有状态:

var initialState = {
  avatar: '/static/uploads/profile-avatars/placeholder.jpg',
  markers: []
};

var UserContext = React.createContext();

function setLocalStorage(key, value) {
  try {
    window.localStorage.setItem(key, JSON.stringify(value));
  } catch (errors) {
    // catch possible errors:
    console.log(errors);
  }
}

function getLocalStorage(key, initialValue) {
  try {
    const value = window.localStorage.getItem(key);
    return value ? JSON.parse(value) : initialValue;
  } catch (e) {
    // if error, return initial value
    return initialValue;
  }
}

function UserProvider({ children }) {
  const [user, setUser] = useState(() => getLocalStorage('user', initialState));
  const [isAvatarUploading, setIsAvatarUploading] = useState(true);
并返回更新数组的函数:

  return (
    <UserContext.Provider
      value={{
        userMarkers: user.markers,
        setUserMarkers: markers => setUser({ ...user, markers }),
      }}
    >
      {children}
    </UserContext.Provider>
  );
假设有一个操作在上面更改此值:

setUserMarkers({"id":1,"lat":40.73977053760343,"lng":-73.55357676744462});
发生的是旧对象被完全覆盖。因此,数组将使用新对象进行更新。没有添加。请帮忙。我也试过concat,但没用

setUserMarkers: markers => setUser(()=> user.markers.concat(markers)),
因此,标记应该是:

  markers: [{"id":0,"lat":40.73977033730345,"lng":-66.55357676744462},{"id":1,"lat":40.73977053760343,"lng":-73.55357676744462}]

像这样调用函数以获取上一个值并附加到它

setUserMarkers([...userMarkers, {"id":1,"lat":40.73977053760343,"lng":-73.55357676744462}])
如果不需要覆盖函数中的值,也可以将函数调用更新为always append。然后您可以使用新值调用它

setUserMarkers: markers => setUser({ ...user, markers: [...user.markers, markers] }),

当您使用
concat
@super时,需要将数组传递给
setUserMarkers
。\n谢谢您的回复,您能提供一个示例吗?谢谢我的朋友!成功了!
setUserMarkers: markers => setUser({ ...user, markers: [...user.markers, markers] }),