Cant find react error which child is missing key prop

强颜欢笑 提交于 2020-01-15 05:40:42

问题


I get the very common Warning: Each child in an array or iterator should have a unique "key" prop. This is usually very easy to resolve but in this case its just impossible to me to figure out where the issue is created.

My stack trace:

 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 Component

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

And the stack goes on but im guessing the issue is somewhere in there. Any clues?


回答1:


In your ProtectedRoutes component you are defining an array and using it somewhere else. Hence, each array needs a key, this is why you are getting warning. So, handle the key for this array.



来源:https://stackoverflow.com/questions/49630833/cant-find-react-error-which-child-is-missing-key-prop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!