2 回答
TA贡献1804条经验 获得超3个赞
代替
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>;
}
TA贡献1825条经验 获得超4个赞
代码沙盒: https://codesandbox.io/s/trusting-rubin-7rcc8
很可能您正在尝试像这样呈现上下文,这会导致错误,而不是解构上下文/用户对象。
// this results in
// Objects are not valid as a React child (found: object with
// keys {username, age}). If you meant to render a collection of
// children, use an array instead.
<Consumer>
{(ctx) => (
<>
{ctx.user}
</>
)
</Consumer>
应用程序.js
import React from "react";
import UserState, { Consumer } from "./UserState";
const Avatar = ({ user }) => (
<>
<div>{user.username}</div>
<div>{user.age}</div>
</>
);
const UserData = () => {
return (
<Consumer>
{(ctx) => (
<>
{ctx.user && (
<>
<Avatar user={ctx.user} />
</>
)}
</>
)}
</Consumer>
);
};
export default function App() {
const userState = {
user: {
username: "hi",
age: 18
}
};
return (
<UserState.Provider value={userState}>
<UserData />
</UserState.Provider>
);
}
用户状态.js
import React from "react";
const UserState = React.createContext({});
export default UserState;
export const { Consumer } = UserState;
添加回答
举报