gpt4 book ai didi

How to access state.entities in reducers for createSlice in Typescript redux-toolkit(如何为类型脚本redux-TOOLKIT中的createSlice访问归约器中的状态实体)

转载 作者:bug小助手 更新时间:2023-10-28 10:18:12 28 4
gpt4 key购买 nike



const questionsAdapter = createEntityAdapter<Question>({
selectId: (question) => question.key,
});

const defaultValue: Question[] = [];
questions.map((question) => {
defaultValue.push(question as Question);
});

const initialState = questionsAdapter.getInitialState();

const questionSlice = createSlice({
name: "questions",
initialState,
reducers: {
fetchQuestions(state) {
questionsAdapter.upsertMany(state, defaultValue);
},
hideQuestion(state, action: PayloadAction<{ key: EntityId }>) {
const { key } = action.payload;
state.entities[key].isVisible = false;
},
}
});

At line state.entities[key].isVisible typescript is throwing below error
Object is possibly 'undefined'.ts(2532) (property) entities: WritableDraft<Dictionary<Question>>

在Statee.Entities[key]行,.isVisible类型的脚本在下方抛出错误对象可能未定义。ts(2532)(属性)实体:WritableDraft<字典<问题>>


How do I solve this issue?

我该如何解决这个问题?


typescript should not throw any errors.

打字稿不应抛出任何错误。


更多回答
优秀答案推荐

Why not? You don’t have any questions in initialState, so your questions gonna be populated only after you run fetchQuestions…

为什么不行?您在InitialState中没有任何问题,因此只有在运行fetchQuestions…之后才会填写您的问题


If you do:

如果您这样做了:


if (state.entities) {

}

that should be sufficient to bypass this error

应该足以绕过这个错误


更多回答

It is still showing the same issue.

它仍然显示相同的问题。

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