提问者:小点点

反应钩,状态未正确改变


在这个项目中,我使用了反应钩,这个片段用来改变项目的颜色主题,但有一个问题,我无法解决。常量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 eusmod tempor incidunt 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.)



共1个答案

匿名用户

初始主题是正文:“{#e2e2e2”,文本:“#363537”}

单击该按钮时,您将记录此主题{body:“#E2E2E2”,text:“#363537”},它正确地是您的初始主题。

日志记录后,将主题更新为暗主题{body:'#363537',text:'#fafafa'}

当您再次单击按钮{body:“#363537”,text:“#fafafa”}时,将记录此信息。

现在问题来了,由于您在每个呈现上创建了darkTheme对象,引用与前面的不同,因此比较else if(theme==darkTheme)失败,因为darkTheme对象与前面的darkTheme对象不同。

或者将主题对象生成移出组件,这样您就不会在每次呈现时生成新的对象,或者将类型添加到主题中:

const lightTheme = {
  body: '#E2E2E2',
  text: '#363537',
  type: "light"
}`

并比较:if(theme.type==darktheme.type)