2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
代替
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貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
代碼沙盒: https://codesandbox.io/s/trusting-rubin-7rcc8
很可能您正在嘗試像這樣呈現(xiàn)上下文,這會(huì)導(dǎo)致錯(cuò)誤,而不是解構(gòu)上下文/用戶對(duì)象。
// 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>
應(yīng)用程序.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>
);
}
用戶狀態(tài).js
import React from "react";
const UserState = React.createContext({});
export default UserState;
export const { Consumer } = UserState;
添加回答
舉報(bào)