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.
它仍然显示相同的问题。
我是一名优秀的程序员,十分优秀!