Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda