英文:
Redux toolkit state property that is dependent on other state property
问题
使用Redux Toolkit,正确的方式来定义一个状态属性,该属性依赖于其他状态属性是什么?我需要类似于以下的内容:
const initialState: AppSliceState = {
words: "",
cursor: 0,
typedChars: words.substring(0, cursor),
remainingChars: words.substring(cursor, words.length - 1),
};
在我的应用中,我从API获取一些文本并将其放入words
属性中。然后,当用户开始输入时,每次键入一个字符,cursor
属性都会增加。例如,如果获取的单词是"Hello!",用户按下H,然后cursor
变为1,typedChars
应该是"H",remainingChars
应该是"ello!"。
我认为我可以在我的应用组件中定义typedChars
,但在这种情况下,我可能需要进行属性传递,我想避免这种情况。
英文:
With redux toolkit what is the correct way of defining one state property that is dependent on other state property? I need something like:
const initialState: AppSliceState = {
words: "",
cursor: 0,
** typedChars: words.substring(0, cursor),
remainingChars: words.substring(cursor, words.length - 1),**
};
In my app I fetch some text from api and put it in words property. Then when user starts typing, cursor property is increased on every typed key. For example if fetched words is "Hello!" and user press H then cursor becomes 1 and typedChars should be "H", and remainingChars should be "ello!"
I think I can define typedChars in my App component but in that case I may have props drilling which I would like to avoid
答案1
得分: 0
这似乎是createSelector
的一个使用案例,因为你正在派生数据:
https://redux.js.org/usage/deriving-data-selectors
const selectWords = state => state.words
const selectCursor = state => state.cursor
const selectTypedChars = createSelector([selectWords, selectCursor], (words, cursor) => {
return words.substring(0, cursor)
})
const selectRemainingChars = createSelector([selectWords, selectCursor], (words, cursor) => {
return words.substring(cursor, words.length - 1)
})
然后在需要时,你可以直接这样做:
const typedChars = useSelector(selectTypedChars)
英文:
This seems like a use case for createSelector
, as you are deriving data:
https://redux.js.org/usage/deriving-data-selectors
const selectWords = state => state.words
const selectCursor = state => state.cursor
const selectTypedChars = createSelector([selectWords, selectCursor], (words, cursor) => {
return words.substring(0, cursor)
})
const selectRemainingChars = createSelector([selectWords, selectCursor], (words, cursor) => {
return words.substring(cursor, words.length - 1)
})
and then where you need it you can just do
const typedChars = useSelector(selectTypedChars)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论