从API获取对象后,如何从对象中获取键值?

时间:2020-08-17 14:31:16

标签: reactjs api fetch jsx

我从API获取对象,并将其存储在状态中。保存了整个对象,因为在显示它时会得到以下输出:

{“ ID”:“ 8”,“ Nombre”:“ Maria Antonieta”,“ Categoria”:“ Romance”,“ Director”:“ nose”}

但是当我尝试显示每个值(例如“ Nombre”)时,出现此错误:

未处理的拒绝(TypeError):无法读取未定义的属性“ Nombre”

这是我的代码(有条件语句中的提取,因为我调用了模态,因此当它打开时,发生提取):

const Modal = ({ handleClose, show, id }) => {
const showHideClassName = show ? "mod displayBlock" : "mod displayNone";
const [peliSeleccionada, setPeli] = useState();

if (show){
    fetch(`http://localhost/APIpeliculas/api/pelicula/read_single.php/?ID=${id}`)
    .then(res => {
        if (res.ok){
           return res.json();
        }else{
            console.log("hubo un problema");
        }
    }).then( peliJson => {
        setPeli(JSON.stringify(peliJson));
        //alert(peliJson);
        //alert(peliSeleccionada);
    });
}

return (
  <div className={showHideClassName}>
    <section className="mod-main">
        <h5>EDITAR: </h5>
        <label> 
            { peliSeleccionada} 
        </label>
        <div className="btn-grupo">
            <button type="button" className="btn btn-success btn-lg btn-block">Guardar cambios</button>
            <button onClick={handleClose} type="button" className="btn btn-secondary btn-lg btn-block">Cerrar</button>
        </div>
    </section>
  </div>
);

};

0 个答案:

没有答案
相关问题