数组中的组件数量listOfComponents应该是动态的。在我的应用程序中,组件在应用程序运行时会随着时间的推移而添加和删除。当我添加一个新组件时,我想listOfComponents在我的ExampleContext. 当我删除一个组件时,我想删除状态。listOfComponents只有在 id 匹配的地方更新了设置,组件才应该重新渲染。我将如何实施呢?
import React, { createContext, useState } from 'react'
export const ExampleContext = createContext()
export const { Consumer: ExampleConsumer } = ExampleContext
export function ExampleProvider({ children }) {
const [state, setState] = useState({
listOfComponents: [{
id: 1,
settings: {color: 'red'}
},
{
id: 2,
settings: {color: 'blue'}
},
{
id: 3,
settings: {color: 'green'}
}]
})
return (
<ExampleContext.Provider value={[state, setState]}>
{children}
</ExampleContext.Provider>
)
}
export function Component({id}) {
const [state, setState] = useContext(ExampleContext)
return (
<h1> Only rerender me if settings of matching id are updated! </h1>
)
}