React useReducer:状态未更新

时间:2021-04-22 05:08:45

标签: reactjs

有人可以帮我弄清楚我的代码有什么问题吗?我创建了以下初始状态:

  const initialIsTouched =
  {
    itemOne:false,
    itemTwo: false
  };

我设置了以下reducer函数:

  const formReducer = (state, action) => {

  switch (action.type) {
    case 'TOUCHED':
      if (action.id == 'itemOne') {
        return {
        [state.itemOne]: true,
        [state.itemTwo]: false
        }               
      }
      if (action.id == 'itemTwo') {
        return {
        [state.itemOne]: false,
        [state.itemTwo]: true
        }              
      }      
    default:
      return state;  
  }
};

我就这样发送了我的动作:

const touchedHandler = event => {
  dispatch({
    type: 'TOUCHED',
    id: event.target.id
  });
};

有人可以向我解释我做错了什么吗?我的状态没有更新。

非常感谢!

2 个答案:

答案 0 :(得分:0)

  const formReducer = (state, action) => {

   switch (action.type) {
    case 'TOUCHED':
    if (action.id == 'itemOne') {
      return {
       itemOne: true,
       itemTwo: false
      }               
    }
    if (action.id == 'itemTwo') {
      return {
        itemOne: false,
        itemTwo: true
      }              
    }      
    default:
       return state;  
   }
 };

答案 1 :(得分:0)

请看看我希望你得到你想要的。

我们可以通过使用 useReducer 钩子来实现这种类型的事情。

import React, {useReducer} from 'react';

const initialState = {
    itemOne: true,
    itemTwo: false
}
const reducer = (state, action) => {
    switch (action.type) {
    case 'TOUCHED':
    if (action.id == 'itemOne') {
      return {
       itemOne: true,
       itemTwo: false
      }               
    }
    if (action.id == 'itemTwo') {
      return {
        itemOne: false,
        itemTwo: true
      }              
    }      
    default:
       return state;  
   }
}

const [state, dispatch] = useReducer(reducer, initialState);

const touchedHandler = event => {
  dispatch({
    type: 'TOUCHED',
    id: event.target.id
  });
};