reactjs - 相同 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
属性,但它仍然无法正常工作。有什么建议吗?
谢谢,
丹麦
解决方案
我发现我的减速器返回了一个全局对象,它导致了一个问题。也就是说,React 存储了我的全局对象,该对象由另一个代码更新,但 reducer 返回相同的对象地址,这导致 React 得出结论该对象保持不变。
推荐阅读
- javascript - 使用超时淡出多个元素仅淡出列表中的最后一个
- ios - 在 Notification Service Extension 中添加日志记录和检索日志
- java - 在同一个项目中同时使用 XGBoostPredictorClassification 和 XGBoostClassification
- python - 将嵌套键和值添加到 dict 对象
- python - 如何在 PyQT5 中创建导航栏
- chart.js - ChartJS 条形图 - 即使光标在条形之外也触发悬停
- javascript - 如何正确使用 react-native-navigation 库中的 Navigation.showOverlay(...)?
- django - 每个模型对象的 Django 返回字段
- excel - 读取 Excel 单元格注释会导致 VBA 错误
- pandas - 日期从月初偏移时的熊猫日期时间频率