为什么我无法在响应中从json读取对象?

时间:2020-05-01 17:53:06

标签: javascript arrays json reactjs

你好,我想做的是导入这个JSON文件:

[
  {
    "nombre":"Is this It",
    "año":" July 30, 2001",
    "genre":"Indie rock",
    "label":"RCA",
    "lugar":"Estados Unidos",
    "portada":"https://www.elquintobeatle.com/wp-content/uploads/2015/05/the-strokes-is-this-it-1-1068x1068.jpg",
    "descripcion":"asdasd.",
    "canciones":[
      {
        "numero":1,
        "titulo":"Is this It"
      },
      {
        "numero":2,
        "titulo":"The Modern Age"
      },
      {
        "numero":3,
        "titulo":"Soma"
      },
      {
        "numero":4,
        "titulo":"Barely Legal"
      },
      {
        "numero":5,
        "titulo":"Someday"
      },
      {
        "numero":6,
        "titulo":"Alone, Together"
      },
      {
        "numero":7,
        "titulo":"Last Nite"
      },
      {
        "numero":8,
        "titulo":"Hard to Explaim"
      },
      {
        "numero":9,
        "titulo":"New York City Cops"
      },
      {
        "numero":10,
        "titulo":"Trying Your Luck"
      },
      {
        "numero":11,
        "titulo":"Take It or Leave It"
      }
    ]
  },
  {
    "nombre":"Room on Fire",
    "año":"2003",
    "genre":"Indie rock",
    "label":"RCA",
    "lugar":"Estados Unidos",
    "portada":"https://upload.wikimedia.org/wikipedia/en/thumb/9/9f/Room_on_Fire_cover.jpg/220px-Room_on_Fire_cover.jpg",
    "descripcion":"asdasd",
    "canciones":[
      {
        "numero":1,
        "titulo":"What Ever Happened"
      },
      {
        "numero":2,
        "titulo":"Reptilia"
      },
      {
        "numero":3,
        "titulo":"Automatic Stop"
      },
      {
        "numero":4,
        "titulo":"12:51"
      },
      {
        "numero":5,
        "titulo":"You Talk Way Too Much"
      },
      {
        "numero":6,
        "titulo":"Between Love & Hate"
      },
      {
        "numero":7,
        "titulo":"Meet Me in the Bathroom"
      },
      {
        "numero":8,
        "titulo":"Under Control"
      },
      {
        "numero":9,
        "titulo":"The Way It Is"
      },
      {
        "numero":10,
        "titulo":"The End Has No End"
      },
      {
        "numero":11,
        "titulo":"I Can't Win"
      }
    ]
  }
]
import * as data from '../catalogo.json';

然后通过一个函数,我像这样更新组件的状态:

updateState(e)
{
    this.setState
    (
        {
            albumActual : data[1]
        }   
    );
}

当我想阅读信息并在桌子上这样写时:

<tr>
    <td className='celda'> Song: </td>
     <td className='celda'> 
       <ul>
            <li>
               <div> 
                    {this.state.albumActual.canciones[1].numero }
                </div> 
               </li>
        </ul>
  </td>

,我遇到以下问题: result

我只是不明白为什么。我只是反应的发展初学者。

这是完整的组件:

从'react'导入React 导入'../assets/css/ComponenteBarra.css'; 从'../catalogo.json'导入*作为数据;

BarraAlbumes类扩展了React.Component { 构造函数(道具) { 超级(道具); this.actualizarState = this.actualizarState.bind(this); this.state = {albumActual:[]} }

actualizarState(e)
{
    this.setState
    (
        {
            albumActual : data[1]
        }   
    );
}

render()
{
    return(
    <div id='barra'>

            <table>
                <thead>
                    <td colSpan='7'>
                        <h1 id='tituloDeBarra' > ALBUMES </h1>
                    </td>
                </thead>
                <tbody>
                <tr>
                    <td> 
                        <button onClick={this.actualizarState}>
                            <img src='https://upload.wikimedia.org/wikipedia/en/thumb/0/09/The_Strokes_-_Is_This_It_cover.png/220px-The_Strokes_-_Is_This_It_cover.png' alt='portada' />
                        </button>
                   </td>

                   <td>
                       <button>
                            <img src='https://upload.wikimedia.org/wikipedia/en/thumb/9/9f/Room_on_Fire_cover.jpg/220px-Room_on_Fire_cover.jpg' alt='portada' />
                       </button>
                   </td>

                   <td > 
                        <button>
                            <img src='https://upload.wikimedia.org/wikipedia/en/thumb/0/0f/FIOEstrokes.jpg/220px-FIOEstrokes.jpg' alt='portada' />
                        </button> 
                   </td>

                   <td >
                       <button>
                                <img src='https://upload.wikimedia.org/wikipedia/en/thumb/d/d9/Strokes_1.jpg/220px-Strokes_1.jpg' alt='portada' />
                       </button>
                   </td>

                   <td > 
                        <button>
                            <img src='https://upload.wikimedia.org/wikipedia/en/thumb/9/91/The_Strokes_-_Comedown_Machine.jpg/220px-The_Strokes_-_Comedown_Machine.jpg' alt='portada' />
                        </button> 
                   </td>

                   <td >
                       <button>
                                <img src='https://upload.wikimedia.org/wikipedia/en/thumb/d/d3/The-Strokes-Future-Present-Past-EP.jpg/220px-The-Strokes-Future-Present-Past-EP.jpg' alt='portada' />
                       </button>
                   </td>

                   <td >
                       <button>
                                <img src='https://upload.wikimedia.org/wikipedia/en/thumb/f/f8/The_Strokes_-_The_New_Abnormal.png/220px-The_Strokes_-_The_New_Abnormal.png' alt='portada' />
                       </button>
                   </td>

                </tr>
                </tbody>
            </table>


            <table id='tableinfo'>
                <thead>
                        <td id='titulotabla' colSpan='2'> INFORMACION DEL ALBUM </td>
                </thead>

                <tbody>
                    <tr>
                        <td className='celda' > Nombre: </td>
                        <td className='celda' > {this.state.albumActual.nombre} </td>
                    </tr>

                    <tr>
                        <td className='celda'> Año de Lanzamiento: </td>
                        <td className='celda'>   {this.state.albumActual.año} </td>
                    </tr>

                    <tr>
                        <td className='celda'> Genero: </td>
                        <td className='celda'>   {this.state.albumActual.genre} </td>
                    </tr>
                    <tr>
                        <td className='celda'> Disquera: </td>
                        <td className='celda'>   {this.state.albumActual.label} </td>
                    </tr>
                    <tr>
                        <td className='celda'> Lugar: </td>
                        <td className='celda'>  {this.state.albumActual.lugar}  </td>
                    </tr>
                    <tr>
                        <td className='celda'> Portada: </td>
                        <td className='celda'> <img src={this.state.albumActual.portada}  alt='foto' /> </td>
                    </tr>
                    <tr>
                        <td className='celda'> Descripcion: </td>
                        <td className='celda'> {this.state.albumActual.descripcion} </td>
                    </tr>
                    <tr>
                        <td className='celda'> Canciones: </td>
                        <td className='celda'> 
                            <ul>
                                <li>
                                     <div> 
                                            {this.state.albumActual.canciones[1].numero }
                                     </div> 
                                </li>
                            </ul>
                        </td>
                    </tr>

                </tbody>
            </table>
    </div>      
    )   
}

}

导出默认的BarraAlbumes;

3 个答案:

答案 0 :(得分:0)

向您展示完整的组件以及如何调用该函数。

但是我非常有信心,问题在于第一次渲染时您的数据还不是数据。

您可以将render方法包装成条件,也可以将状态设置为默认值。

import * as data from '../catalogo.json';


class App extends React.Component {
  constructor(props) {
    super(props);

    // Set the state directly. Use props if necessary.
    this.state = {
      albuls: data
    }
  }
}

答案 1 :(得分:0)

这是一个示例解决方案:

主要要点是必须检查是否存在要输出的变量。

const data = [{
    "nombre": "Is this It",
    "año": " July 30, 2001",
    "genre": "Indie rock",
    "label": "RCA",
    "lugar": "Estados Unidos",
    "portada": "https://www.elquintobeatle.com/wp-content/uploads/2015/05/the-strokes-is-this-it-1-1068x1068.jpg",
    "descripcion": "asdasd.",
    "canciones": [{
        "numero": 1,
        "titulo": "Is this It"
      },
      {
        "numero": 2,
        "titulo": "The Modern Age"
      },
      {
        "numero": 3,
        "titulo": "Soma"
      },
      {
        "numero": 4,
        "titulo": "Barely Legal"
      },
      {
        "numero": 5,
        "titulo": "Someday"
      },
      {
        "numero": 6,
        "titulo": "Alone, Together"
      },
      {
        "numero": 7,
        "titulo": "Last Nite"
      },
      {
        "numero": 8,
        "titulo": "Hard to Explaim"
      },
      {
        "numero": 9,
        "titulo": "New York City Cops"
      },
      {
        "numero": 10,
        "titulo": "Trying Your Luck"
      },
      {
        "numero": 11,
        "titulo": "Take It or Leave It"
      }
    ]
  },
  {
    "nombre": "Room on Fire",
    "año": "2003",
    "genre": "Indie rock",
    "label": "RCA",
    "lugar": "Estados Unidos",
    "portada": "https://upload.wikimedia.org/wikipedia/en/thumb/9/9f/Room_on_Fire_cover.jpg/220px-Room_on_Fire_cover.jpg",
    "descripcion": "asdasd",
    "canciones": [{
        "numero": 1,
        "titulo": "What Ever Happened"
      },
      {
        "numero": 2,
        "titulo": "Reptilia"
      },
      {
        "numero": 3,
        "titulo": "Automatic Stop"
      },
      {
        "numero": 4,
        "titulo": "12:51"
      },
      {
        "numero": 5,
        "titulo": "You Talk Way Too Much"
      },
      {
        "numero": 6,
        "titulo": "Between Love & Hate"
      },
      {
        "numero": 7,
        "titulo": "Meet Me in the Bathroom"
      },
      {
        "numero": 8,
        "titulo": "Under Control"
      },
      {
        "numero": 9,
        "titulo": "The Way It Is"
      },
      {
        "numero": 10,
        "titulo": "The End Has No End"
      },
      {
        "numero": 11,
        "titulo": "I Can't Win"
      }
    ]
  }
]

class Album extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      albumActual: {}
    }
    this.updateState = this.updateState.bind(this)
  }

  updateState() {
    this.setState({
      albumActual: data[1]
    })
  }

  render() {
    return (
      <div>
        <button onClick = {this.updateState}>Click</button>
        <ul>
        {
          !this.state.albumActual.canciones
            ? null
            : this.state.albumActual.canciones.map(e => {
              return (
                <li>{e.numero}: {e.titulo}</li>
              )
            })
        }
        </ul>
      </div>
    )
  }
}

ReactDOM.render( <Album /> , document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

因此,您可以更改此内容:

{this.state.albumActual.canciones[1].numero }

{
  !this.state.albumActual.canciones
    : null
    ? this.state.albumActual.canciones[1].numero
}

答案 2 :(得分:0)

最初,单击按钮后(在actualizarState函数中),将setState设置为data [1]时,this.state.albumActual是空数组。因此,请用以下代码替换 {this.state.albumActual.canciones [1] .numero}

{this.state.albumActual.canciones? this.state.albumActual.canciones[1].numero : null}