反应挂钩,状态未正确更改

时间:2020-01-08 13:31:41

标签: javascript reactjs react-hooks

在此项目中,我使用react挂钩,此代码段用于更改项目的颜色主题,但是存在我无法解决的问题。 const 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坐下来,奉献己任,sius do eiusmod tempor incididunt ut labour 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.)


3 个答案:

答案 0 :(得分:4)

初始主题为body: '{#E2E2E2', text: '#363537'}

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

登录后,将主题更新为深色主题{body: '#363537', text: '#FAFAFA'}

再次单击按钮{body: "#363537", text: "#FAFAFA"},将记录下来。

现在出现了问题,因为您在每个渲染器上都创建了darkTheme对象,所以引用与先前的对象并不相同,因此比较else if(theme == darkTheme)失败了,因为darkTheme对象与先前的darkTheme对象不同。 / p>

将主题对象的生成移出组件,这样就不必在每个渲染器上都生成新的对象,也不必在主题上添加类型:

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

并进行比较:if(theme.type == darkTheme.type)

答案 1 :(得分:1)

您需要的是在单击按钮时切换主题:

所以您可以这样做:

ThemeState

import React, { useReducer } from "react";
import { TOGGLE_THEME } from "./ActionTypes";
import ActionReducer from "./ActionReducer";

const lightTheme = {
  body: "#E2E2E2",
  text: "#363537"
};

const darkTheme = {
  body: "#363537",
  text: "#FAFAFA"
};

const initialState = {
  isLightTheme: true
};

export const ThemeState = ({ children }) => {
  const [state, dispatch] = useReducer(ActionReducer, initialState);

  const { isLightTheme } = state;

  const themeToggler = e => {
    e.preventDefault();
    dispatch({ type: TOGGLE_THEME });
  };

  const backgroundColor = isLightTheme ? lightTheme.body : darkTheme.body;
  const fontColor = isLightTheme ? lightTheme.text : darkTheme.text;

  return (
    <div style={{ backgroundColor: `${backgroundColor}` }}>
      <p style={{ color: `${fontColor}` }}>Some Text</p>
      <button type="submit" onClick={themeToggler}>
        Toggle Theme
      </button>
      <hr />
      Current Theme: {isLightTheme ? "light" : "dark"}
    </div>
  );
};

ActionReducer:

import { TOGGLE_THEME } from "./ActionTypes";

export default function(state, action) {
  switch (action.type) {
    case TOGGLE_THEME:
      return {
        ...state,
        isLightTheme: !state.isLightTheme
      };
    default:
      return state;
  }
}

ActionTypes:

export const TOGGLE_THEME = "TOGGLE_THEME";

Codesandbox

答案 2 :(得分:0)

我创建了一个关于此行为could be implemented的最小示例:

const darkTheme = {
  color: "green"
};

const lightTheme = {
  color: "red"
};

export default function App() {
  const [useLightTheme, setUseLightTheme] = useState(true);

  return (
    <div className={useLightTheme ? darkTheme.color : lightTheme.color}>
      <button onClick={() => setUseLightTheme(!useLightTheme)}>toggle</button>
      some example text
    </div>
  );
}

由于您未提供所有相关代码(例如reducer),因此我无法解释您的代码。