如何在修改和呈现状态的组件中使用React Redux存储



Text组件中,我想从DB中获取text_data一次,并将其保存到Redux存储中。


export default function Text() {
const [document, setDocument] = useState([]);
setDocument(useSelector(currentState))
useEffect(() => {
axios.get(`/api/texts/${docId}`).then((response) => {
dispatch(currentState(response.data));
})
}, [])
return (
<div className="Text">
{document.text && document.text.map((text, index) => (
<div onClick={() => {dispatch(changeColor(index))}}>
{text.word}
</div>
))}
</div>
)
}

然后我想从Redux商店获得text_data,可能在同一组件中

setDocument(useSelector(currentState))

但它会引起无限的重复。

此外,我想通过单击来修改text_data,以便Text组件在单击后显示不同颜色的文本。为此,我想修改Redux状态并重新发送Text组件。

text_data具有{word: color, second_word: color, ...}结构

如何使用Redux?有可能吗,我的想法正确吗,重叠状态应该是唯一应该改变的东西?

EDIT:添加了代码段。我正在处理这个问题,所以我的代码片段不起作用。

我认为您没有正确理解react redux钩子。这两条线没有道理。我不知道您的代码片段中的currentState变量应该是什么。但是用法肯定是错误的。

setDocument(useSelector(currentState))
dispatch(currentState(response.data));

我不知道你们的redux商店是什么样子的。在接下来的片段中,我将假设它是这样的。

// redux store structure
{
texts: {document: {}, coloredWords: {}}
}
// fetched document will have structure something like this (array of words)
{text: []}

你的(文本(还原器应该像这样修改redux存储(只是示意性地写的(

// ...
// storing fetched document
case 'SET_DOCUMENT': {
const document = action.payload
return {...state, document: document}
}
// storing color for word at particular index
case 'CHANGE_COLOR': {
const {index, color} = action.payload
return {...state, coloredWords: {...state.coloredWords, [index]: color}}
}
// ...
import { useDispatch, useSelector } from 'react-redux'
import { setDocument, changeColor } from 'path_to_file_with_action_creators'
export default function Text() {  
const dispatch = useDispatch()
// get fetched document from your redux store (it will be an empty object in the first render, while fetch in the useEffect hook is called after the first render)
const document = useSelector(state => state.texts.document))
// get colors for document words (they were saved in redux store by your onClick handler, see bellow)
const coloredWords = useSelector(state => state.texts.coloredWords))
useEffect(() => {
// fetch document
axios.get(`/api/texts/${docId}`).then((response) => {
// store fetched document in your redux store
dispatch(setDocument(response.data));
})
}, [])
return (
<div className="Text">
{document && document.text && document.text.map((text, index) => (
<div
style={{color: coloredWords[index] ? coloredWords[index] : 'black' }}
onClick={() => {
// store color for word at particular index in redux store
dispatch(changeColor({index: index, color: 'red'}))
}}
>
{text.word}
</div>
))}
</div>
)
}

最新更新