首页 > 解决方案 > 为什么 React Context 对对象和数组的行为不同?

问题描述

所以我正在尝试构建一个基本的主题转换器应用程序,但在中途我尝试放置对象值。

这是存储样式表的对象。

 const Theme = {
light:{
    textColor:"#000",
    backgroundColor:"#fff"
},
dark:{
    textColor:"#fff",
    backgroundColor:"#000"
}}

导出默认主题;

案例 1:我尝试在上下文和状态中使用数组作为默认值

const themeContext = createContext(["light"]);
const theme = useContext(themeContext)[0];//theme is whatever is in context array
 const currentTheme = Theme[theme]//current theme will be the value of themecontext in 0th position in array
 const themeHook = useState("light"); //write theme in state, so when app starts it has a default theme at that time

案例 2:现在如果我尝试将默认值添加为对象,它不起作用:

const themeContext = createContext(Theme.dark);
const theme = useContext(themeContext);
const currentTheme = theme;
const themeState = useState(Theme.dark);

我用它来访问数据:

<h1
        style={{
                color:`${currentTheme.textColor}`,
                backgroundColor:`${currentTheme.backgroundColor}`
            }}
        >
        Hello Boiss
        
        </h1>

谁能告诉我为什么?

标签: reactjsreact-hooksreact-context

解决方案


推荐阅读