How to use patchState vs setState in NGXS?

て烟熏妆下的殇ゞ 提交于 2019-12-14 00:18:41

问题


I am learning ngxs but I can't understand when should I use patchState and setState? What's the difference?

const state = ctx.getState();
let data =  this.service.list();
ctx.setState({
    ...state,
    feedAnimals: data
});

vs.

let data =  this.service.list();
ctx.patchState({
    feedAnimals: data
});

回答1:


Those two pieces of code are equivalent. patchState is just a short hand version of the setState({...state, ... } code.

In future patchState will most likely be evolving to a more useful immutability helper with equality testing (ie. the state would only be changed if the patch actually changes any values) and patch operators (this is still in discussion).

I would recommend using patchState for neatness and to take advantage of features that are on their way.




回答2:


IT DOESN'T WORK PROPERLY

const state = context.getState();
state.permissions = action.payload;
context.setState(state);

IT WORKS

const state = context.getState();
state.permissions = action.payload;
context.setState({ ...state });

IT WORKS

const state = context.getState();
state.permissions = action.payload;
context.patchState(state);

All the examples update the state... but the first one doesn't activate the observable for state changes, because state is immutable, that means you cannot simple edit it and save it, it is not editable and you always will have to clone the old state, edit your new copy and save this new state. patchState just does it for you.



来源:https://stackoverflow.com/questions/50462965/how-to-use-patchstate-vs-setstate-in-ngxs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!