【发布时间】:2021-03-15 22:53:53
【问题描述】:
我在我的 React 应用程序中使用钩子来处理状态。
我的应用程序有notes,这些categoryId 与类别相关联。
通过安装NoteList 组件来显示特定类别中的注释。
<NoteList categoryObj={categoryObj} />
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)
选择器
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
}
)
我创建了notesToRender,因为有时我需要在渲染注释之前对其进行过滤(此处未显示该代码)。
在类别之间切换(props.categoryObj.id 更新)时,注释无法正确显示。
加载应用时状态正确,但在类别之间切换时 useEffect 以某种方式导致状态“落后一步”。
- A 类 - 初始负载 - 正常
- 切换到“B 类” - console.log() 显示正确的 categoryId,但来自 A 类的注释
- 切换到“A 类” - console.log() 显示正确的 categoryId,但来自 B 类的注释
- 切换到“B 类” - console.log() 显示正确的 categoryId,但来自 A 类的注释
...等等
选择器的控制台日志显示正确的注释。
问题可能是mapStateToProps 在 useEffect 之后触发?
如何确保mapStateToProps 在之前触发 useEffect 而不会导致不必要的重新渲染 === 仅当 props.categoryObj.id 更改时?
亲切的问候 /K
【问题讨论】:
标签: javascript reactjs react-hooks mapstatetoprops