gpt4 book ai didi

javascript - "Objects are not valid as a React child. If you meant to render a collection of children, use an array instead."错误

转载 作者:行者123 更新时间:2023-12-05 00:36:43 29 4
gpt4 key购买 nike

我正在尝试通过 user对象作为我的 React Context.Provider 的值如 <UserContext.Provider value={user} /> .然而,React 不喜欢将对象作为子对象传递的想法。这是我收到的错误消息:

Error: Objects are not valid as a React child (found: object with keys{id, username, first_name, last_name, email, avatar}). If you meant torender a collection of children, use an array instead.


我希望有人能帮忙。这是我的 React 组件,所有这些都发生在这里:
class MyApp extends App {
constructor(props) {
super(props);
this.state = {
user: {},
authenticating: false,
};
}

logout = () => {
...
};

render() {
const { Component, pageProps } = this.props;
const user = {
user: this.state.user,
logout: this.logout,
};
return (
<>
{!this.state.authenticating && (
<UserContext.Provider value={user}>
<Navbar />
<Component {...pageProps} />
</UserContext.Provider>
)}
</>
);
}
}
有趣的是,当我改变
const user = {
user: this.state.user,
logout: this.logout,
};
到(例如)
const user = {
username: this.state.user.username,
logout: this.logout,
};
一切都很好。
所以(正如上面的错误消息所暗示的那样)问题在于传递 this.state.user给我的上下文提供者。为什么?我该如何解决这个问题?
另外,这是我的 <Context.Consumer /> :
  <UserContext.Consumer>
{user => (
<>
{user.user ? (
<>
<Avatar user={user.user} />
<Button onClick={user.logout}>Logout</Button>
</>
) : (
<>
<Nav.Link href="/users/login">Log in</Nav.Link>
<Nav.Link href="/users/signup">Sign up</Nav.Link>
</>
)}
</>
)}
</UserContext.Consumer>

最佳答案

代替

function Avatar({ user }) {
return <Nav.Link href="/users/login">{user}</Nav.Link>;
}
function Avatar({ user }) {
return <Nav.Link href="/users/login">{user.something}</Nav.Link>;
}

关于javascript - "Objects are not valid as a React child. If you meant to render a collection of children, use an array instead."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63898737/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com