[英]Error while using React Context API: "TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))"
[英]React - When using Hooks, I get an error - Object is not iterable (cannot read property Symbol (Symbol.iterator))
我在LessonThemes組件中使用鈎子,使用上下文,我嘗試訪問Test組件中的color
值,但出現錯誤
Object 不可迭代(無法讀取屬性符號(Symbol.iterator))
課程主題.jsx
import React, {useState, useEffect, createContext} from "react";
import ThemeContext from "./ThemeContext";
export const CounterContext = createContext();
export default function LessonThemes(props) {
const [color, setColor] = useState(localStorage.getItem("color"));
const [themes, setThemes] = useState([
{ name: "G", color: "green" },
{ name: "R", color: "red" },
{ name: "B", color: "blue" },
])
useEffect(() => {
localStorage.setItem("color", color);
})
const SideBarPageContent = (SideBarPageContentBackground) => {
localStorage.setItem('color', SideBarPageContentBackground);
setColor(SideBarPageContentBackground);
}
return (
<CounterContext.Provider value={[color, setColor]}>
{
themes.map((theme, index) => {
return (
<label key={index}>
<input
onChange={() => SideBarPageContent(theme.color)}
type="radio"
name="background"
/>{theme.name}</label>
);
})
}
</CounterContext.Provider>
);
}
測試.jsx
export default function Test(props) {
const [color] = useContext(LessonThemes);
return (
<div>
<div className="sidebar-brand-container">
<LessonThemes />
</div>
<div>
<span style={{ background: color }} href="#">Theme</span>
</div>
</div>
);
}
LessonThemes
是一個反應組件,它為它的孩子提供上下文。 CounterContext
是您需要在Test
中訪問的上下文。
import { CounterContext } from '../path/to/CounterContext';
export default function Test(props) {
const [color] = useContext(CounterContext);
return (
<div>
<div className="sidebar-brand-container">
<LessonThemes />
</div>
<div>
<span style={{ background: color }} href="#">Theme</span>
</div>
</div>
);
}
您可能還應該定義一個初始上下文值,以防Test
沒有被渲染到一個以CounterContext
作為祖先的 React DOMTree 中。
export const CounterContext = createContext([]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.