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

164
Visualizações
why we use arrayed property instead of using it directly

My question is why we use [action.fieldName]: action.payload?

Why we couldn't use action.fieldName: action.payload?

import './App.css';
import React,{useReducer} from 'react';

const initialState = {
  username: "",
  password: "",
  isLoggedIn: false,
  error: false,
};

function reducer(state, action){
  switch(action.type){
    case "FIELD_CHANGE":
      return {
        ...state,
        [action.fieldName]: action.payload,
      }

    default:
      return state;
  }
}

function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const { username, password, isLoggedIn, error } = state;
  console.log(state);
  return (
    <div className="App">
      <label htmlFor="username">Username: </label>
      <input type="text" name="username" onChange={(e)=> dispatch({type:"FIELD_CHANGE",fieldName:"username",payload:e.target.value})}/>

      <label htmlFor="password">Password: </label>
      <input type="text" name="password" onChange={(e)=> dispatch({type:"FIELD_CHANGE",fieldName:"password",payload:e.target.value})}/>

      <div>
        {username}
      </div>
    </div>
  );
}

export default App;

I understand that there will be more than one fieldName but once we specify them individually using ...state it should automatically add since it will be different input name (username & password).

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

0

why we couldn't use action.fieldName: action.payload

You cannot use action.fieldName as key as it will throw error. You can use 'action.fieldName' but the key name will not be the value of action.fieldName . In order to use the value of action.fieldName as object key name you need to use []

[] is called Computed Property Names, its implemented using bracket notation( square brackets) []

about 4 years ago · Juan Pablo Isaza Relatório

0

For example, if you write the code :

const myFirstObject={property1:"cool",property2:"bad"}
const testObject={[myFirstObject.property1]:myFirstObject.property2}
console.log(testObject);

in your console, you have:

{cool: "bad"}
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