类型错误:状态值未定义
2022-01-30
178
我正在制作一个评论组件,其中我从本地存储的 json 文件中获取数据。我将数据导入变量 data 中,并将其相应字段设置为我的状态值。但是当我通过上下文传递数据时,它说数据未定义。
data.json
{
"currentUser": {
"image": {
"png": "./images/avatars/image-juliusomo.png",
"webp": "./images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
},
"comments": [
{
"id": 1,
"content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
"createdAt": "1 month ago",
"score": 12,
"user": {
"image": {
"png": "./images/avatars/image-amyrobson.png",
"webp": "./images/avatars/image-amyrobson.webp"
},
"username": "amyrobson"
},
"replies": []
}
]
}
这是我存储和传递数据的方式 context.js
import data from "./data";
const AppContext = React.createContext();
const AppProvider = ({ children }) => {
const { comments, setComments } = useState(data.comments);
const { currUser, setCurrUser } = useState(data.currentUser);
return (
<AppContext.Provider value={{ comments, currUser }}>
{children}
</AppContext.Provider>
);
};
这是我收到错误的地方 App.js
import { useGlobalContext } from "./context";
const App = () => {
const { comments, currUser } = useGlobalContext();
...
}
1个回答
useState
钩子返回一个数组,而不是一个对象。使用数组解构赋值。第一个元素是状态值,第二个元素是状态更新函数。
const AppProvider = ({ children }) => {
const [comments, setComments] = useState(data.comments);
const [currUser, setCurrUser] = useState(data.currentUser);
return (
<AppContext.Provider value={{ comments, currUser }}>
{children}
</AppContext.Provider>
);
};
Drew Reese
2022-01-30