Redux工具包中依赖于其他状态属性的状态属性

huangapple go评论84阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年6月6日 02:55:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76409254.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定