gpt4 book ai didi

reactjs - Normalizr + Redux - 更新单个实体的属性

转载 作者:行者123 更新时间:2023-12-03 14:28:22 26 4
gpt4 key购买 nike

我正在构建一个音乐播放器应用程序,并使用 REST API 从各个端点获取轨道(播放列表、特定用户发布的轨道等)

我正在使用 redux 和 normalizr 来管理我的状态。我创建了一个 tracks 实体,用于映射 track 对象及其 id。

简而言之,我的状态看起来有点像这样:

{
playlists: {
123: { id: 123, name: 'foo', tracks: [1, 2, 3] }
},
users: {
me: { name: 'Niek', tracks: [2, 3] },
},
entities: {
tracks: {
1: { name: 'bar', user_favorited: false, ... },
2: { name: 'foo', user_favorited: false, ... },
3: { name: 'bar', user_favorited: true, ... }
}
}
}

到目前为止,这对我来说效果很好。但现在我正在构建通过调用另一个 API 端点来切换轨道的收藏状态的功能。

此端点在响应中不包含整个 track 资源,但我确实想更新单个 trackuser_favorited 属性API调用成功后的实体。

实现这一目标的最佳方法是什么?

作为一种解决方法,我现在在 user_favorited 端点调用成功后再次从另一个端点获取整个 track 实体,但我希望找到一个优雅的解决方案没有必要这样做的地方。

最佳答案

将提出两种解决方案:

  1. 重新获取数据。

  2. 更改实体。

实现此目的的一种方法是创建一个如下所示的实体缩减器:

const tracksReducer = (state, action) => {
// Change the tracks
}

const entitiesReducer = (state, action) => {
let _state = state;

// Store all entities
if (action.payload && action.payload.entities) {
_state = merge({}, state, action.payload.entities);
}

return combineReducers({
tracks: tracksReducer,
})(_state, action);
};

export default { entities: entitiesReducer };

* 上面的代码使用了 lodash 中的 merge 和 redux 中的 combineReducers

<小时/>

Lately I've been also thinking about another structure completely, but haven't tested it nor found anybody else sharing their experiences with it. The idea would be do remove the first level "entities" completely and storing them under the corresponding key. Theoretically it seems to make sense when we start to make changes to entities and would be easier to keep all similar reducers, selectors etc. in a single place.

{
tracks: {
entities: {
1: { name: 'bar', user_favorited: false, ... },
2: { name: 'foo', user_favorited: false, ... },
3: { name: 'bar', user_favorited: true, ... }
},
top3: [1, 2, 3],
somethingAboutTracks: true
},
users: {
entities: {},
me: { name: 'Niek', tracks: [2, 3] }
},
playlists: {
entities: {
123: { id: 123, name: 'foo', tracks: [1, 2, 3] }
}
}
}

关于reactjs - Normalizr + Redux - 更新单个实体的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43298766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com