React -当使用Hooks时,我得到一个错误-对象不是可迭代的(不能读取属性Symbol (Symbol.itera



我使用钩子在LessonThemes组件,使用上下文,我尝试访问Test中的color值组件,但我得到一个错误

对象不可迭代(不能读取属性Symbol (Symbol.iterator))

LessonThemes.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

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是一个react组件,它为它的子组件提供上下文。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([]);

相关内容