[英]React Hook useEffect() - Run after mapStateToProps
I am using hooks in my React application to handle state.我在我的 React 应用程序中使用钩子来处理 state。
My application has notes
that are associated to categories by categoryId
.我的应用程序具有通过
categoryId
与类别相关联的notes
。
Notes in a specific category are shown by mounting a NoteList
component.通过挂载
NoteList
组件来显示特定类别中的笔记。
<NoteList categoryObj={categoryObj} />
The NoteList
functional component NoteList
功能组件
export const NoteList = (props) => {
const [notesToRender, setNotesToRender] = useState(props.notes)
useEffect(() => {
console.log('I fired!', props.categoryObj.id, props.notes)
setNotesToRender(props.notes)
}, [props.categoryObj.id]);
//...
return (
notesToRender.map((note) => {
return <NoteListItem key={note.id} {...note}/>
}
)
}
const mapStateToProps = (state) => {
notes: getNotesForCategory(state) // Selector that returns notes where note.id === props.categoryObj.id
}
export default connect(mapStateToProps)(NoteList)
Selector选择器
export const getNotesForCategory = createSelector(
[getNotes, getcategoryId],
(notes, categoryId) => {
const categoryNotes = notes.filter(note => note.id === categoryId)
console.log('categoryNotes ', categoryNotes) // This log shows the correct notes
return categoryNotes
}
)
I create notesToRender
since I sometimes need to filter the notes before rendering them (that code is not shown here).我创建
notesToRender
因为有时我需要在渲染注释之前过滤它们(此处未显示该代码)。
When switching between categories ( props.categoryObj.id
updates) the notes does not show correctly.在类别(
props.categoryObj.id
更新)之间切换时,注释无法正确显示。
When loading the app the state is correct, but when switching between categories the useEffect somehow causes the state to be "one step behind".加载应用程序时,state 是正确的,但在类别之间切换时,useEffect 会以某种方式导致 state “落后一步”。
... and so on ... 等等
The console log from the selector shows the correct notes.选择器的控制台日志显示了正确的注释。 The problem might be that
mapStateToProps
triggers after the useEffect?问题可能是
mapStateToProps
在 useEffect之后触发? How can I make sure mapStateToProps
triggers before the useEffect without causing unnecessary re-renders === only when props.categoryObj.id
changes?如何确保
mapStateToProps
在 useEffect之前触发,而不会导致不必要的重新渲染 === 仅当props.categoryObj.id
更改时?
Kind regards /K亲切的问候/K
For me, the solution seems to be to change the useEffect() dependency from props.categoryObj.id
to props.notes
.对我来说,解决方案似乎是将 useEffect() 依赖项从
props.categoryObj.id
为props.notes
。 My only hurdle now is how to compare two arrays of objects in the useEffect() dependency.我现在唯一的障碍是如何比较 useEffect() 依赖项中的两个 arrays 对象。
Things I have tested so far are:到目前为止我测试过的东西是:
I have posted a new question here --> React useEffect(): Most efficient way to compare if two arrays of objects are equal我在这里发布了一个新问题 --> React useEffect(): Most Effective way to compare if two arrays of objects are equal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.