不可变 setIn 嵌套对象返回无效的 keyPath 错误
Immutable setIn nested object returning invalid keyPath error
我有以下对象:
const initialState = Map({
posts: {
most_popular: [],
trending: [],
latest: [],
}
});
我正在尝试更新条目中的子对象。这是我尝试过的:
intialState.setIn(["posts", "most_popular"], ["array", "of", "values"]);
运行 这个设置命令将 return
Uncaught Error: Invalid keyPath()
我错过了什么吗?我不需要创建子地图,对吗?例如
const initialState = Map({
posts: Map({
most_popular: [],
显然这行不通(我试过了),但也许还有另一种设置子对象的方法?
编辑:
获取对象并像这样更新:
state.get("entries").most_popular = ["k"];
但这意味着我的 entries.most_popular(趋势,最新)不是一成不变的?有没有办法让子对象不可变?
不使用 Map()
,而是使用 fromJS()
。如果你使用Map()
,那么你的键most_popular
下的数组是一个标准的JS对象,而不是Immutable.js结构。
因此:
const initialState = fromJS({
posts: {
most_popular: [],
trending: [],
latest: [],
}
});
现在一切都是不可变对象。那么你可以轻松做到:
initialState.setIn(["posts", "most_popular"], ["array", "of", "values"]);
我有以下对象:
const initialState = Map({
posts: {
most_popular: [],
trending: [],
latest: [],
}
});
我正在尝试更新条目中的子对象。这是我尝试过的:
intialState.setIn(["posts", "most_popular"], ["array", "of", "values"]);
运行 这个设置命令将 return
Uncaught Error: Invalid keyPath()
我错过了什么吗?我不需要创建子地图,对吗?例如
const initialState = Map({
posts: Map({
most_popular: [],
显然这行不通(我试过了),但也许还有另一种设置子对象的方法?
编辑:
获取对象并像这样更新:
state.get("entries").most_popular = ["k"];
但这意味着我的 entries.most_popular(趋势,最新)不是一成不变的?有没有办法让子对象不可变?
不使用 Map()
,而是使用 fromJS()
。如果你使用Map()
,那么你的键most_popular
下的数组是一个标准的JS对象,而不是Immutable.js结构。
因此:
const initialState = fromJS({
posts: {
most_popular: [],
trending: [],
latest: [],
}
});
现在一切都是不可变对象。那么你可以轻松做到:
initialState.setIn(["posts", "most_popular"], ["array", "of", "values"]);