Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

226
Visualizações
React redux - useSelect() and useDispatch() when mapping objects
//state.buttons is an array - it is used to map buttons to a menu

function NavMenu() {
  const buttons = useSelector((state) => state.buttons);
  const dispatch = useDispatch();

  const navButtons = buttons.map((button) => {
    const checkDirection = (button) => {
      if (button.pageNo >= button.prevPageNo) {
        dispatch(updateButtonsData({ newDirection: 1 }));
      } else {
        dispatch(updateButtonsData({ newDirection: -1 }));
      }
    };
    checkDirection(button);

    return (
      <li key={button.id} >
          <NavButton buttonData={button} />
      </li>
    );
  });

  return <ul>{navButtons}</ul>;
}

export default NavMenu;


//buttonSlice 

const initialState = [
  {
    id: 'homeId',
    prevPageNo: null,
    pageNo: 1,
    direction: 1,
    firstAnimFrame: 1,
    lastAnimFrame: 1,
  },
  {
    id: 'aboutId',
    prevPageNo: null,
    pageNo: 2,
    direction: 1,
    firstAnimFrame: 1,
    lastAnimFrame: 11,
  },{...}

const buttonsSlice = createSlice({
  name: 'ui',
  initialState,
  reducers: {
    updateButtonsData: {
      reducer(state, action) {
        state = action.payload;
      },
      prepare(
        id,
        newPrevPageNo,
        pageNo,
        newDirection,
        newFirstFrame,
        newLastFrame
      ) {
        return {
          payload: {
            id,
            prevPageNo: newPrevPageNo,
            pageNo,
            direction: newDirection,
            firstAnimFrame: newFirstFrame,
            lastAnimFrame: newLastFrame,
};},},},},});

Hello, I have a navigation menu where several parameters must be dynamically updated within the UI when a user presses a button. Each button will behave differently depending on the previous button as pressed (order of pressed buttons matters). My solution is to compare the initial state of the nav buttons array to each subsequent remapping. I thought it would be good to store the history of the previously pressed button as a value inside the nav objects array. Each time the navigation is refreshed, new parameters are added and accessible as props inside the mapped button and can then be accessed onClick.

Currently, the dispatch function does not work with my code, and the mapped buttons array remains unchanged.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I assume that you are "triggering" the update data via checkDirection(button); and not onClick Event.

first this is a "no-go" code:

  const navButtons = buttons.map((button) => {
    const checkDirection = (button) => {
      if (button.pageNo >= button.prevPageNo) {
        dispatch(updateButtonsData({ newDirection: 1 }));
      } else {
        dispatch(updateButtonsData({ newDirection: -1 }));
      }
    };
    checkDirection(button);

    return (
      <li key={button.id} >
          <NavButton buttonData={button} />
      </li>
    );
  });

  return <ul>{navButtons}</ul>;
}

If you want to trigger a function while rendering an element, put it inside useEffect and not "outside".

So, transfer that code inside NavButton like:

    const checkDirection = useCallback(button) => {
      if (button.pageNo >= button.prevPageNo) {
        dispatch(updateButtonsData({ newDirection: 1 }));
      } else {
        dispatch(updateButtonsData({ newDirection: -1 }));
      }
    }, []);

   useEffect(() => checkDirection(button), [checkDirection, button]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda