반응형
Vuex - Normalizr이 예상대로 작동하지 않음
간단한 채팅 앱을 만들고 있습니다.방, 메시지, 사용자라는 세 가지 엔티티가 있습니다.다음과 같은 응답을 반환하는 가짜 API를 가지고 있습니다.
[{
id: 1,
name: 'room1',
avatar: 'some img url',
messages: [
{
id: 1,
text: 'some text',
user: {
id: 1,
username: 'Peter Peterson',
avatar: 'some img url'
}
]
}]
제 행동은 이렇습니다.
getAllRooms({ commit }) {
commit(GET_ALL_ROOMS_REQUEST);
return FakeApi.getAllRooms()
.then(
rooms => {
const { entities } = normalize(rooms, room);
console.log(entities);
commit(GET_ALL_ROOMS_SUCCESS, {
rooms: entities.rooms, byId: rooms.map(room => room.id)
});
commit(GET_ALL_MESSAGES_SUCCESS, { messages: entities.messages });
commit(GET_ALL_USERS_SUCCESS, { users: entities.users });
},
err => commit(GET_ALL_ROOMS_ERROR)
)
}
내 돌연변이는 이렇게 생겼지
[GET_ALL_ROOMS_REQUEST](state) {
state.loading = true;
},
[GET_ALL_ROOMS_SUCCESS](state, payload) {
state.rooms = payload.rooms;
state.byId = payload.byId;
state.loading = false;
},
[GET_ALL_ROOMS_ERROR]() {
state.error = true;
state.loading = false;
}
내 컴포넌트는 동작을 다음과 같이 호출합니다.
{
mounted() {
this.getAllRooms();
}
}
스키마 정의는 다음과 같습니다.
const user = new schema.Entity('users');
const message = new schema.Entity('messages', {
user: user
});
const room = new schema.Entity('rooms', {
messages: [message]
})
FakeApi.getAllRooms() 이후 메서드로 응답을 체크하면 모든 오브젝트가 이상한 옵저버로 랩되어 정상화 및 정상화 시 이상한 응답이 반환됩니다.
내가 뭘 잘못하고 있지?
문제는 vuejs가 아니라 내가 정규 스키마를 만드는 방법에 있었다.내 응답은 루트에 배열이 있기 때문에 새로운 것이 필요했습니다.rooms
다음과 같은 어레이 스키마:
const user = new schema.Entity('users');
const message = new schema.Entity('messages', {
user: user
});
const room = new schema.Entity('rooms', {
messages: [message]
});
const roomsSchema = [room];
그리고 이렇게 사용하세요.normalize(rooms, roomsSchema)
언급URL : https://stackoverflow.com/questions/52120046/vuex-normalizr-doesnt-work-as-expected
반응형
'programing' 카테고리의 다른 글
MySQL에 SHA1 해시 값 저장 (0) | 2022.09.30 |
---|---|
MySQL 트리거에서 테이블 업데이트를 막는 오류 발생 (0) | 2022.09.30 |
마리아답서비스:마운트 네임스페이스를 설정하지 못함: 사용 권한이 거부됨/NAMESPACE 산포 단계에서 실패했습니다. (0) | 2022.09.30 |
왼쪽 조인 표시는 업데이트 가능합니까? (0) | 2022.09.30 |
C의 문자열에서 지정된 인덱스의 문자를 제거하려면 어떻게 해야 합니까? (0) | 2022.09.30 |