【发布时间】:2020-04-26 01:21:27
【问题描述】:
在这个项目中我使用了react hooks,这个sn-p用来改变项目的颜色主题,但是有一个我无法解决的问题。 常量 lightTheme = { ... }
const darkTheme = {
...
}
export const ThemeState = ({children}) => {
const initialState = {
theme: lightTheme
}
const [state, dispatch] = useReducer(ActionReducer, initialState)
const {theme} = state
const themeToggler = (e) => {
e.preventDefault()
console.log(theme)
if(theme == lightTheme){
dispatch({type:THEME, payload: darkTheme})
}
else if(theme == darkTheme){
dispatch({type:THEME, payload: lightTheme})
}
}
Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。
我的减速机:
export const ActionReducer = (state, action) => {
switch(action.type) {
case THEME:
return{
...state,
theme: action.payload
}
default:
return state
}
};
Here is component with toggle button by each click, I need to change theme in state, it clicks correctly:
import {ThemeContext} from '../../store/themeState'
function Main () {
const {theme, themeToggler} = useContext(ThemeContext)
return (
<button onClick={e => {themeToggler(e)}}></button>
)
}
export default Main
when I press the button i catch this log
({body: "#E2E2E2", text: "#363537"}
{body: "#363537", text: "#FAFAFA"}
{body: "#363537", text: "#FAFAFA"}
....)
I don't know why do state changes like this. If you can, help me to solve this bug.)
【问题讨论】:
-
你能添加你的 ActionReducer 以及你在哪里 console.log 状态吗?
-
您需要发布您的 ActionReducer 和主题 reducer 代码,以便我们帮助您找到任何问题
-
@Domino987,我固定了减速器
-
你在哪里记录它;)
-
@Domino987 在 if 运算符之前,看看
标签: javascript reactjs react-hooks