首页 > 解决方案 > 相同 React 组件类型的多个实例无法正确呈现

问题描述

我是新手 React 开发人员。我正在尝试制作一个获取信息列表的组件(即下面代码中的 InfoList.currentList。)并将其呈现为多个元素。为了帮助我的模型代码触发重新渲染,相关组件使用 useReducer() 注册了一个触发函数。这是我最小化的代码(仍然产生同样的问题。)

function BannerStyleInfoView() {
  function reducer(state: {[index: number]: any}, action: any) {
    return InfoList.currentList()
  }

  const [currentList, dispatch] = useReducer(reducer, {})
  useEffect(function() {
    InfoList.forceRender = () => {dispatch(undefined)}
    return () => {InfoList.forceRender = undefined}
  }, [])

  const elements = Object.entries(currentList).map(function([index, entry]) {
    // @ts-ignore
    const {text} = entry
    console.debug("=== Added", index, text)
    return (
        <BannerStyleInfoElement key={index} index={index} text={text} />
    )
  })
  console.log("=== elements:", elements)

  return (
    <>
      {elements}
    </>
  )
}

function BannerStyleInfoElement({index, text}: {index: string, text: string}) {
  console.debug("=== show:", index, text)
  return (
      <div key={index}> {text} </div>
  )
}

class InfoList {
  public static initialize() {
    infoList = {}
  }

  public static append(text:string, duration: number = 2) {
    const entry = {
      duration,
      text,
      timestamp: Date.now()
    }
    let indexString
    indexString = nextIdentifier.toString()
    ++nextIdentifier
    infoList[indexString] = entry

    if (InfoList.forceRender) {
      InfoList.forceRender()
    }

    return indexString
  }

  public static clear(identifier: string) {
    console.assert(identifier in infoList)
    delete infoList[identifier]
  }

  public static currentList() {
    return infoList
  }

  public static forceRender: (() => void) | undefined
}
export {InfoList}


let nextIdentifier = 0
let infoList: {[index: string]: any} = {}

在上面的代码中,我调用InfoList.append()了两次。当它第一次被调用时,代码正确地发出一个<div>. 但是第二次调用不会重新渲染。日志消息如下所示。

=== Added 0 entry0
=== elements: [{…}]
=== show: 0 entry0

=== Added 0 entry0
=== Added 1 entry1
=== elements: (2) [{…}, {…}]

我的观察是第二次调用没有=== show日志消息,而第一次调用正确地发出了日志消息。我怀疑这与处理同一组件类型的多个实例有关,但我不确定。我添加了key属性,但它仍然无法正常工作。有什么建议吗?

谢谢,

丹麦

标签: reactjs

解决方案


我发现我的减速器返回了一个全局对象,它导致了一个问题。也就是说,React 存储了我的全局对象,该对象由另一个代码更新,但 reducer 返回相同的对象地址,这导致 React 得出结论该对象保持不变。


推荐阅读