数组listOfComponents
中的组件数应该是动态的。在我的应用程序中,在应用程序运行时,组件会随着时间的推移而添加和删除。当我添加一个新组件时,我想在我的ExampleContext
的listOfComponents
数组中为它添加一个状态。当我删除组件时,我想删除状态。仅当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>
)
}
这是我如何让它与useMemo
一起工作的。也许这对其他人有帮助,因为我花了一些时间来弄清楚。这篇博文也非常有帮助。如果有更好的方法,请告诉我。
-- 应用.js
import React, {useContext, useMemo} from 'react';
import {ExampleContext, ExampleProvider} from './Context'
export function Component({id}){
const [state, setState] = useContext(ExampleContext)
function onClick(){
setState(prev => {
return {...prev, [id]: { color: 'blue'}}
})
}
return useMemo(() => {
console.log(`update ${id}`)
return (
<>
<h1 style={{color: state[id].color}}>{id}</h1>
<button onClick={onClick}>{`Update from ${id}`}</button>
</>
)
}, [state[id]])
}
function App() {
return (
<ExampleProvider>
<Component id={1}/>
<Component id={2}/>
</ExampleProvider>
);
}
export default App;
-- 上下文.js
import React, { createContext, useState } from 'react'
export const ExampleContext = createContext()
export const { Consumer: ExampleConsumer } = ExampleContext
export function ExampleProvider({ children }) {
const [state, setState] = useState({
'1': {color: 'red'},
'2': {color: 'green'},
})
return (
<ExampleContext.Provider value={[state, setState]}>
{children}
</ExampleContext.Provider>
)
}