找不到react错误哪个孩子缺少关键props

IT技术 reactjs jsx
2021-04-28 20:13:13

我得到了一个非常常见的警告:数组或迭代器中的每个子项都应该有一个唯一的“键”属性。这通常很容易解决,但在这种情况下,我无法弄清楚问题是在哪里产生的。

我的堆栈跟踪:

 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;
}

连接保护路由

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;
            }}
        />
    );
};

堆栈还在继续,但我猜问题出在那里。有什么线索吗?

1个回答

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