简体   繁体   English

我的 map function 在反应 js 中不起作用

[英]My map function is not working in react js

import React, { Component } from "react";
import { TextField } from "@material-ui/core";
import SearchResult from "./SearchResult";

class Search extends Component {
    constructor() {
    super();
    this.state = {
        data: [],
    };
    this.renderRes = this.renderRes.bind(this);
    }
    handelTextFieldChange(e) {
    fetch(`http://localhost:8000/api/search-post?query=${e.target.value}`)
        .then((res) => res.json())
        .then((data) => {
        this.setState({
            data: data,
        });
        console.log(this.state.data);
        });
    }
    renderRes() {
    return (
        <div>
        {Array(this.state.data).map((_, index, blog) => {
            return (
            <SearchResult
                content={blog[index]["body"]}
                date={String(blog[index]["date"])}
                author={blog[index]["author"]}
                title={blog[index]["title"]}
            />
            );
        })}
        </div>
    );
    }
    render() {
    return (
        <div id="search">
        <div className="search-box">
            <TextField
            id="outlined-basic"
            label="Enter any Keyword"
            variant="outlined"
            onChange={(e) => this.handelTextFieldChange(e)}
            />
        </div>
        <div className="search-results">{this.renderRes()}</div>
        </div>
    );
    }
}

export default Search;

My fetch data --->我的获取数据--->

[
{"author": "Pranav Tripathi",
 "title": "What is Diet?", "body": "In nutrition, diet is the sum of food consumed by a person or other organism.[1] The word diet often implies specific nutrition intake for health or weight-management reasons (with the two often being related). Although humans are omnivores, each culture and each person holds some food preferences or some food taboos. This may be due to personal tastes or ethical reasons. Individual dietary choices may be more or less healthy. Complete nutrition requires ingestion and absorption of vitamins, minerals, essential amino acids from protein and essential fatty acids from fat-containing food, also food energy in the form of carbohydrates, protein, and fat. Dietary habits and choices play a significant role in the quality of life, health, and longevity.", 
"date": "2021-05-23 21:15:13.603332+00:00",
 "post_id": "ABCDEF"}
]

There is more of it but I am sending the first one because others are mostly the same.还有更多,但我要发送第一个,因为其他大部分都相同。

When I was debugging.在我调试的时候。 It mostly gives undefined.它主要给出未定义的。 I have made the API in Django.我在 Django 中制作了 API。 From the backend side, it works well.从后端来看,它运行良好。 But from the front end, it doesn't.但从前端来看,它没有。 I am fresher in react I am making the project to learn it, therefore, the react code is not industry standard我对反应更新鲜我正在制作项目来学习它,因此,反应代码不是行业标准

if you data is an array why dont you just如果你的数据是一个数组,你为什么不只是

 return (
                  <SearchResult
                    content={blog.body}
                    date={blog.date}
                    author={blog.author}
                    title={blog.title}
                />
 )
})

or you can just simple pass {...blog} to your component或者您可以简单地将 {...blog} 传递给您的组件

your data is already in array so you dont need to convert it an array again,which is the main cause of you are getting undefined,and another point is the mapping callback,it will get blog as first argument and index as second,so the correct way to map result is as follow您的数据已经在数组中,因此您不需要再次将其转换为数组,这是导致未定义的主要原因,另一点是映射回调,它将博客作为第一个参数,索引作为第二个,所以map 结果的正确方法如下

 renderRes() {
    return (
        <div>
        {this.state.data.map((blog,index) => {
            return (
            <SearchResult
                content={blog["body"]}
                date={String(blog["date"])}
                author={blog["author"]}
                title={blog["title"]}
            />
            );
        })}
        </div>
    );
    }

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

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