我正在尝试为一个小项目设置主题提供程序。每次用户单击按钮时,应用程序主题(颜色)都应该改变。假设我在一个单独的文件中有四个主题,如下所示:
const themesArray = [
{ primaryColor: '#483639', secondaryColor: '#F7F7F7' },
{ primaryColor: '#fb7051', secondaryColor: '#333' },
{ primaryColor: '#60b494', secondaryColor: '#F7F7F7' },
{ primaryColor: '#afb5c0', secondaryColor: '#333' }
];
export default themesArray;
每次用户单击按钮(嵌套在特定组件中)时,计数器都会递增,直到 3,如下所示:
import React, { useState, useContext } from 'react';
import themesArray from '../../styles/themesArray';
const ThemeContext = React.createContext();
const ThemeUpdateContext = React.createContext();
const useTheme = () => useContext(ThemeContext);
const useThemeUpdate = () => useContext(ThemeUpdateContext);
const ThemeProvider = ({ children }) => {
const [state, setState] = useState({
count: 0,
primaryColor: themesArray[0].primaryColor,
secondaryColor: themesArray[0].secondaryColor
});
const toggleTheme = () => {
setState(prevState => ({
count: prevState.count >= 3 ? 0 : ++prevState.count,
primaryColor: themesArray[prevState.count].primaryColor,
secondaryColor: themesArray[prevState.count].secondaryColor
}));
}
return (
<ThemeContext.Provider value={[state.primaryColor, state.secondaryColor]}>
<ThemeUpdateContext.Provider value={toggleTheme}>
{children}
</ThemeUpdateContext.Provider>
</ThemeContext.Provider>
);
}
export { ThemeProvider, useTheme, useThemeUpdate };
计数器似乎工作正常,但问题是我永远不会回到我的第一个对象值(我永远不会回到第一个主题颜色)。我的意思是当我console.log(state.count, state.primaryColor, state.secondaryColor)
得到这个时:
0 #483639 #F7F7F7 ThemeContext.js:24
1 #fb7051 #333 ThemeContext.js:24
2 #60b494 #F7F7F7 ThemeContext.js:24
3 #afb5c0 #333 ThemeContext.js:24
0 #afb5c0 #333 ThemeContext.js:24
1 #fb7051 #333 ThemeContext.js:24
2 #60b494 #F7F7F7 ThemeContext.js:24
3 #afb5c0 #333 ThemeContext.js:24
0 #afb5c0 #333 ThemeContext.js:24
你知道为什么每次计数器值回到 0 时,第一个对象值都会被最后一个对象值覆盖吗?