【问题标题】:React Hook useEffect() - Run after mapStateToPropsReact Hook useEffect() - 在 mapStateToProps 之后运行
【发布时间】: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 以某种方式导致状态“落后一步”。

  1. A 类 - 初始负载 - 正常
  2. 切换到“B 类” - console.log() 显示正确的 categoryId,但来自 A 类的注释
  3. 切换到“A 类” - console.log() 显示正确的 categoryId,但来自 B 类的注释
  4. 切换到“B 类” - console.log() 显示正确的 categoryId,但来自 A 类的注释

...等等

选择器的控制台日志显示正确的注释。 问题可能是mapStateToProps useEffect 之后触发? 如何确保mapStateToProps 之前触发 useEffect 而不会导致不必要的重新渲染 === 仅当 props.categoryObj.id 更改时?

亲切的问候 /K

【问题讨论】:

    标签: javascript reactjs react-hooks mapstatetoprops


    【解决方案1】:

    对我来说,解决方案似乎是将 useEffect() 依赖项从 props.categoryObj.id 更改为 props.notes。 我现在唯一的障碍是如何比较 useEffect() 依赖项中的两个对象数组。

    到目前为止我测试过的是:

    1. props.notes.length --> 有效但不可靠 - 原因很明显:)
    2. ...props.notes --> 如果数组不为空但可能会导致严重的性能问题?

    我在这里发布了一个新问题 --> React useEffect() : Most efficient way to compare if two arrays of objects are equal

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 2019-10-08
      • 1970-01-01
      • 2021-11-13
      • 2019-05-27
      • 2019-04-14
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多