简体   繁体   中英

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. 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

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

 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>
    );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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