Home > OS >  Javascript - React. Object's existing property shows undefined
Javascript - React. Object's existing property shows undefined

Time:01-18

I have an object which is passed with props. I can console.log the object correctly, but when I try to console.log the properties, they are shown as undefined

TodoList.js

import React from 'react';
import {TodoItem} from './TodoItem.js';

export function TodoList({todos}){
    return (
        <ul>
            {
                todos.map(
                    function(campos){
                        console.log('list.texto: ', campos.texto);
                        return(
                            <TodoItem props={campos} />
                        );
                    }
                )
            }
        </ul>
    );
}

TodoItem.js. Look at the console.logs

import React from 'react';

export function TodoItem(props){
  console.log('item: ', props);
  console.log('item.texto1: ', props.texto);
  console.log('item.texto2: ', props["texto"]);
  return (
    <li>
      <h4>Estado</h4>
      <p>{props["estado"]}</p>
      <h4>Fecha Apertura</h4>
      <p>{props["fechaApertura"]}</p>
      <h4>Texto</h4>
      <p>{props["texto"]}</p>
    </li>
  );
}

Items are rendered "fine" but empty and the code logs the following:

> list.texto:  "Muestra" TodoList.js:10

> item: TodoItem.js:4
  Object {
  "props": {
    "estado": 0,
    "fechaApertura": "2000-01-01",
    "fechaCierre": "2020-01-01",
    "texto": "Muestra"
  }
}

> item.texto1:  undefined TodoItem.js:5

> item.texto2:  undefined TodoItem.js:6

WHY ARE HE PROPERTIES UNDEFINED? Thanks in advance.

CodePudding user response:

You've got two different things that you're naming props. First, you're passing in an individual prop named props:

<TodoItem props={campos} />

But then on the receiving end, props is the entire props object. The value you passed in would be on props.props:

export function TodoItem(props){

One way you can fix this is by using destructuring to assign props.props. to a variable named props:

export function TodoItem({ props }){

Or, consider renaming the prop to cause less confusion:

<TodoItem item={campos} />
// ...
export function TodoItem({ item }){

CodePudding user response:

Hi because your object layer has one more layer.

You can pass parameters using destructuring assignment like ({ props }) or use as the following example

const props = {
  "props": {
    "estado": 0,
    "fechaApertura": "2000-01-01",
    "fechaCierre": "2020-01-01",
    "texto": "Muestra"
  }
}

console.log('item: ', props);
console.log('item.texto: ', props['props']['texto']);

  •  Tags:  
  • Related