繁体   English   中英

返回json对象以呈现方法-React.js

[英]Return json object to render method - React.js

我正在将pokeapi用于个人项目,并且想在做的同时学习React。 一旦设法从api检索需求信息,像这样:

handleSubmit(event) {

        axios.get('https://pokeapi.co/api/v2/pokemon/' + this.state.input_id).then(r => {

            var data = r.data;
            var types = [];
            for (let i = 0; i < data.types.length; i++) types.push(data.types[i].name);

            const pokemon = {
                id: data.id,
                name: data.name,
                sprite: data.sprites.front_default,
                height: data.height,
                weight: data.weight,
                types: types,
            };

            this.setState({
                pokemon: pokemon
            });

        }).catch(e => {

            console.log(e);

        }); // axios

        event.preventDefault();

    } // handleSubmit

我想要的就是渲染这个神奇宝贝对象。 这就是我现在正在做的事情:

render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <label>
                        Pokemon's id
                        <input type="text" value={this.state.input_id} onChange={this.handleChange} />
                    </label>
                    <input type="submit" value="Find!"/>
                </form>
                <code>{this.state.pokemon}</code>
            </div>
        );
    } // render

当然,这将引发下一个错误:

Objects are not valid as a React child (found: object with keys {id, name, sprite, height, weight, types}). If you meant to render a collection of children, use an array instead.

有没有一种方法可以在表格内渲染此对象? 我想这是不会在状态内部保存数据的,但是我不知道该怎么做。

React不允许您将对象作为React子对象,因此您可以先使用JSON.stringify将其放入字符串中:

<code>{JSON.stringify(this.state.pokemon)}</code>

您不能直接在react中打印对象或数组。 尽管{JSON.stringify(this.state.pokemon)}确实可以工作,并允许您将对象作为字符串打印出来,但如果需要,也可以单独打印对象属性。

您可以通过将{this.state.pokemon}更改为类似代码来修复代码-

{this.state.pokemon.id}
{this.state.pokemon.name} 
{this.state.pokemon.sprite}
{this.state.pokemon.height}
{this.state.pokemon.weight}
{this.state.pokemon.types}

尽管反应不允许渲染对象。 您可以创建一个并行的函数来渲染并将对象传递给它,然后在该函数中进行渲染; 像下面这样。

_render(obj){
   return <code>{obj}</code> //here also jsx syntax are valid.
}

render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <label>
                        Pokemon's id
                        <input type="text" value={this.state.input_id} onChange={this.handleChange} />
                    </label>
                    <input type="submit" value="Find!"/>
                </form>
                {this._render(this.state.pokemon)}
            </div>
        );
    } // render

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM