在运行时将React web组件状态与上下文状态共享



我有一个设置列表,这些设置用作运行时实例化web组件的数据。每次使用主<应用程序/>将在运行时查找并呈现该项。该组件使用useContext进行存储。

// ComponentContext initial state
const initialState = {  components: [] } // components example state ['a', 'b', 'c']
// component source
export function getComponent(id) { 
const ComponentA = () => {
const [info] = useState([1,2,3]);
return (<div>A</div>)
}        
const ComponentA = () => {
const [info] = useState([3,4,5]);
return (<div>A</div>)
}        
const componentMap = {
a: ComponentA,
b: ComponentB
}
}
// App component
function App() {
const { add, components }  = useContext(ComponentContext);
return <div className="flex">
<button onClick={add('a')}>add a</button>
<button onClick={add('b')}>add b</button>
<button onClick={add('c')}>add c</button>
{components.map(id => {
const Component = componentMap[id];
return <Component key={id}/>
})}
</div>

稍后在程序中,我想打印出组件实例和信息数组项。创建每个组件后,信息数组项保持不变。问题是,保存在组件上下文中的组件列表不包含有关信息数组的信息(可能看起来像这样[‘a’,b’,‘a’’,‘c’…等等],所以我不能使用组件列表遍历层次结构。此外,信息数组是在运行时随机生成的,与组件本身无关。

看起来我应该将我的initialState更改为以下内容:

// ComponentContext initial state
// example state [{ id: 'a', info: [...] }, { id : 'c', info: [...] }]
const initialState = {  components: [] } 

由于添加组件方法无法访问信息数组,我如何在存储新添加的组件时设置信息列表?

我认为没有办法从外部访问组件状态(至少没有干净的(。

"上下文";旨在用于此目的:在组件之间共享状态。组件自身的状态(useState(应该只存储这一个组件所需的数据。

我认为你应该设计你的父状态(ComponentContext(,这样每个组件都可以访问它需要的所有数据。

此外,你还说;信息数组。。。与组件本身无关",所以我认为信息应该与其他东西有关,因此应该可以将数据存储在这个">其他东西";,并使组件从那里接收数据。

您可以将数据添加到某个存储中,而不是使用add函数创建组件。然后,当您想要显示组件时,您可以迭代(.map(((存储而不是组件列表,并"动态"创建组件。以同样的方式,你会访问你想"去哪里"的同一家商店;"打印输出";信息。

最新更新