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

gz5pxeao  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(144)

使用redux工具包,定义一个依赖于其他状态属性的状态属性的正确方法是什么?我需要类似的东西:

const initialState: AppSliceState = {
  words: "",
  cursor: 0,
 ** typedChars: words.substring(0, cursor),
  remainingChars: words.substring(cursor, words.length - 1),**
};

在我的应用程序中,我从API中获取一些文本并将其放入words属性中。然后,当用户开始键入时,光标属性在每个键入的键上增加。例如,如果获取的单词是“Hello!用户按H键,光标变为1,typedChars应为“H”,remainingChars应为“ello!“
我想我可以在我的应用程序组件中定义typedChars,但在这种情况下,我可能会有 prop 钻取,我想避免

o75abkj4

o75abkj41#

这看起来像是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)

相关问题