javascript - 我无法显示对象 Promise (react) 的内容

标签 javascript reactjs jsx

我是 React 新手,有一个问题。 当我在select中选择一个选项时,我想用innerHTML显示该选项的数据。当我执行 console.log(data) 时,我从请求中获取数据。但是,在我的页面上,我得到 [object Promise] 或 [object Object] 而不是数据。 我已经做了几个星期了,但我做不到,请帮助我!

PS:抱歉我的英语不好,我是法国人:)。

这里是我在 jsx 中的代码:

import React from 'react';
import {Link} from "react-router-dom";
import axios from "axios";
import Select from "../../components/forms/Select";

class Persons extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            render: false,
            error: null,
            isLoaded: false,
            persons: [],
            person: [],
            id: ''
        };
        //this.handleChange = this.handleChange.bind(this);
    }

    fetchPersons() {
        return axios .get("'http://localhost:8000/api/persons")
            //.then(res => res)
            .then((result) => {
                console.log("result: ",result);
                this.setState({
                    isLoaded: true,
                    persons: result.data["hydra:member"]
                })
            }),
            (error) => {
                this.setState({
                    isLoaded: true,
                    error
                })
                console.log(error);
            }
    }

    async fetchPerson(id) {
        console.log(id);
        try {
            return await fetch("'http://localhost:8000/api/persons/" + id)
                .then(res => res.json())
                .then((result) => {
                    console.log("rr " + result); //object Object
                    this.setState({
                        isLoaded: true,
                        person: result.data
                    })
                    console.log("result1: ",result);
                    return result;
                })
        }catch(error) {
            this.setState({
                error
            })
            console.log("Erreur: ", error);
        }
    }

    componentDidMount() {
        this.fetchPersons();
    }

    handleChange = (event) => {
        const show = document.getElementById("show");
        console.log("I'm in handleChange");
        const value = event.target.value;
        let select = this.fetchPerson(value);
        console.log("Select: " + select);
        console.log("Select2: " , [select]);
        console.log("Select: " + [{select}]);
        console.log("Select2: " , [{select}]);
        let newContent =  "You selected " + JSON.stringify([{select}]);
        show.innerHTML = newContent;
    }

    render() {
        const {error, isLoaded, persons, person} = this.state;
        if (error) {
            return <div>Erreur : {error.message}</div>;
        } else if (!isLoaded) {
            return <div>Chargement…</div>;
        } else {

            return (
                <div id="show">
                    <h1>Test</h1>
                    <Select id="selectPerson" name="persons"  label="Persons" value={persons.id} onChange={this.handleChange.bind(this)}>
                        <option key={0} value={null}>Choice</option>
                        {this.state.persons && this.state.persons.map(person => (
                            <option key={person.id} value={person.id}>{person.ref} </option>
                        ))}
                    </Select>

                    {this.state.persons && this.state.persons.map(person =>
                        <tr key={person.id}>
                            <td>{person.lname}</td>
                            <td>{person.fname}</td>
                            <td>{person.sexe}</td>
                            <td>{person.age}</td>
                        </tr>)}
                </div>
            )

        }
    }

};

export default Persons;


最佳答案

您的 fetchPerson 函数是异步,但您的 handleChange 函数不会等待它。

handleChange = (event) => { // <-------- Need to make this function async
        const show = document.getElementById("show");
        console.log("I'm in handleChange");
        const value = event.target.value;
        let select = this.fetchPerson(value); // <----------- Need to wait on this with await
        console.log("Select: " + select);
        console.log("Select2: " , [select]);
        console.log("Select: " + [{select}]);
        console.log("Select2: " , [{select}]);
        let newContent =  "You selected " + JSON.stringify([{select}]);
        show.innerHTML = newContent;
    }

关于javascript - 我无法显示对象 Promise (react) 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65849890/

相关文章:

javascript - 理解 Eloquent JavaScript 函数式编程中的 apply 方法示例

javascript - JQuery ajax 加载 XML,不适用于 IE 或 Edge

javascript - 条件发布事件

javascript - 为什么在 DOM 渲染中将属性设置为等于自身 - React.js

javascript - 如何在 typescript 中导出类型,它将类型标记为未定义

css - 为什么我的媒体查询没有优先于我的内联 JSX 样式?

javascript - React ajax 和 jsx

javascript - 如何下载由 JavaScript 生成的文件,避免自动打开 Chome?

reactjs - Material UI - 自定义 IconButton,带有像真实 Button 一样的变体 Prop

reactjs - React map 中的键问题