【问题标题】:Share React web component state with context state at runtime在运行时与上下文状态共享 React Web 组件状态
【发布时间】:2020-12-13 05:16:51
【问题描述】:

我有一个设置列表,这些设置用作在运行时实例化 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: [] } 

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

【问题讨论】:

    标签: reactjs use-context


    【解决方案1】:

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

    “上下文”旨在用于此目的:在组件之间共享状态。组件自己的状态(useState)应该只存储这个组件单独需要的数据。

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

    另外,你说“信息数组......与组件本身无关”,所以我认为信息应该与其他东西有关,因此应该可以将数据存储在这个“其他东西”中,并让组件从那里接收数据。

    您可以将数据添加到某个存储区,而不是使用add 函数创建组件。然后,当您想要显示组件时,您将迭代 (.map()) 存储而不是组件列表,并“即时”创建组件。以同样的方式访问要“打印”信息的同一商店。

    【讨论】:

    • 当然列表与组件本身有关,否则我不会把它们放在那里。我说随机是因为每种类型的组件都有一个不同的列表,它不是随机的,而是组件独有的。
    猜你喜欢
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2020-08-07
    相关资源
    最近更新 更多