【问题标题】:Why can't I dynamically create context providers in react?为什么我不能在反应中动态创建上下文提供程序?
【发布时间】:2020-09-13 13:28:51
【问题描述】:

这是我实现这一目标的尝试,但我似乎无法让它发挥作用:

import React from 'react'

/**
 * Example of input:
 * [
 *  {
 *    Context: React.createContext(),
 *    value: { test: "hello" }
 *  },
 *  {
 *    Context: React.createContext(),
 *    value: { test: "world" }
 *  }
 * ]
 */

const recursive = (contexts, children) => {
    if(contexts.length < 1) return children;
    const { Context, value } = contexts[0];
    
    return (
        <Context.provider value={ value }>
            { recursive(contexts.shift()) }
        </Context.provider>
    )
}

function Contexts({ contexts, children }) {

    return (    
        <>
        { recursive(contexts, children) }
        </>
    )
}

export default Contexts;

这甚至可以做到吗?如果可以,我能做到吗?

我使用递归函数的原因是因为有子组件需要存在于上下文提供程序中。

【问题讨论】:

  • 一个问题肯定是你直接改变了道具。你应该在shift之前slice

标签: reactjs react-hooks


【解决方案1】:

我注意到这是否是唯一的错误,但您对shift 的使用不正确。

shift 修改数组并返回删除的对象。这意味着

{ recursive(contexts.shift()) }

会将contexts[0](已删除的元素)传递给递归调用,它还将更改从props 传递的context 数组。更改 props 始终是一个危险的错误。

要正确地将值传递给下一个调用,您必须创建一个数组副本:

const copy = contexts.slice();
copy.shift();

...
{ copy }

不过,还有一种更简单的写法:

if (contexts.length === 0) {
  return children;
}

const [{ Context, value }, ...otherContexts] = contexts;

return (
    <Context.provider value={value}>
        {otherContexts}
    </Context.provider>
)

【讨论】:

    猜你喜欢
    • 2022-07-22
    • 2020-08-15
    • 2019-06-07
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2016-04-07
    • 2021-12-31
    相关资源
    最近更新 更多