[英]React - When using Hooks, I get an error - Object is not iterable (cannot read property Symbol (Symbol.iterator))
I use hooks inside the LessonThemes component, using the context, I try to access the color
value inside the Test component, but I get an error我在LessonThemes组件中使用钩子,使用上下文,我尝试访问Test组件中的
color
值,但出现错误
Object is not iterable (cannot read property Symbol (Symbol.iterator)) Object 不可迭代(无法读取属性符号(Symbol.iterator))
LessonThemes.jsx课程主题.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>
);
}
Test.jsx测试.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
is a react component, it's providing the context to its children. LessonThemes
是一个反应组件,它为它的孩子提供上下文。 CounterContext
is the context you need to access in Test
. 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>
);
}
You should probably also define an initial context value in case Test
isn't being rendered into a React DOMTree with a CounterContext
as an ancestor.您可能还应该定义一个初始上下文值,以防
Test
没有被渲染到一个以CounterContext
作为祖先的 React DOMTree 中。
export const CounterContext = createContext([]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.