【问题标题】:Cant find react error which child is missing key prop找不到哪个孩子缺少关键道具的反应错误
【发布时间】:2018-09-12 19:47:36
【问题描述】:

我得到了一个非常常见的警告:数组或迭代器中的每个孩子都应该有一个唯一的“key”道具。这通常很容易解决,但在这种情况下,我不可能找出问题的根源。

我的堆栈跟踪:

 in hoc (created by Connect(hoc))
    in Connect(hoc) (at withTranslation.js:7)
    in hoc (at ConnectedProtectedRoutes.js:26)
    in Route (at ConnectedProtectedRoutes.js:44)
    in ProtectedRoutes (created by Connect(ProtectedRoutes))

withTranslation 组件

export function withTranslation(CMP) {
    var hoc = class extends React.Component {
        render() {
            return <CMP {...this.props} translate={translate} />
        }
    };
    return hoc;
}

ConnectedProtectedRoutes

const ProtectedRoutes = ({ token, authority, location }) => {
    var a = [
        createRouteWithRequirements(<Login key="1"/>, "/", [], { token, authority }, true),
        createRouteWithRequirements(<Login key="2"/>, "/login", [], { token, authority }),
        createRouteWithRequirements(<Register key="3"/>, "/register", [], { token, authority })
    ]

    return a
};

const createRouteWithRequirements = (component, url, requirements, injections, exact) => {
    return (
        <Route //this is -> in Route (at ConnectedProtectedRoutes.js:44)
            exact={!!exact}
            key={url}
            path={url}
            render={() => {
                if (requirements.includes("token") && !injections.token) {
                    return <Redirect to="/login" />
                }

                return component;
            }}
        />
    );
};

堆栈还在继续,但我猜问题出在某个地方。有什么线索吗?

【问题讨论】:

  • 您是否在父组件中渲染任何其他可能具有相同键的内容(例如key="1")?如果您同时挂载了两个单独的列表,并且某些列表元素具有相同的键,则会出现警告。

标签: reactjs jsx


【解决方案1】:

在 ProtectedRoutes 组件中,您正在定义一个数组并在其他地方使用它。因此,每个数组都需要一个密钥,这就是您收到警告的原因。所以,处理这个数组的键。

【讨论】:

  • 让我试试,我确信在定义这样的数组时,索引被用作键。 brb
  • 仍然出现错误,如 EDIT 中所示进行了更改,很确定我过去也尝试过。事实上,我可以看到我将整个 url 作为密钥传递(忘记了我什至这样做是为了避免这个问题)
  • 我不是专业人士,但我很确定键不会自动处理数组:) 我确信这会解决问题。我现在在您的代码中看不到任何导致该错误的原因。
  • 我知道吗?这已经在我的控制台中弹出太久了,你可以想象强迫症触发
猜你喜欢
  • 2021-09-29
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 2018-09-28
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
相关资源
最近更新 更多