Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在react中使用axios从内部联接表获取数据时出现问题_Reactjs_Express_Axios_Field - Fatal编程技术网

Reactjs 在react中使用axios从内部联接表获取数据时出现问题

Reactjs 在react中使用axios从内部联接表获取数据时出现问题,reactjs,express,axios,field,Reactjs,Express,Axios,Field,我是react的新手,所以我尝试将使用axios的express返回的数据放在字段中,但在显示联接表中的数据时遇到了一些问题 import React, { Component } from "react"; import FilmesDataService from "../services/filmes.service"; export default class Tutorial extends Component { constructor(props) { s

我是react的新手,所以我尝试将使用axios的express返回的数据放在字段中,但在显示联接表中的数据时遇到了一些问题

import React, { Component } from "react";
import FilmesDataService from "../services/filmes.service";

export default class Tutorial extends Component {
    constructor(props) {
        super(props);
        this.onChangeTitle = this.onChangeTitle.bind(this);
        this.onChangeDescription = this.onChangeDescription.bind(this);
        this.onChangeFoto = this.onChangeFoto.bind(this);
        this.onChangeGenero = this.onChangeGenero.bind(this);
        this.getTutorial = this.getTutorial.bind(this);
        this.updateTutorial = this.updateTutorial.bind(this);
        this.deleteTutorial = this.deleteTutorial.bind(this);

        this.state = {
            dataProduto: {},
            message: ""
        };
    }

    componentDidMount() {
        this.getTutorial(this.props.match.params.id);
    }

    onChangeTitle(e) {
        const titulo = e.target.value;

        this.setState(function(prevState) {
            return {
                dataProduto: {
                    ...prevState.dataProduto,
                    titulo: titulo
                }
            };
        });
    }

    onChangeDescription(e) {
        const descricao = e.target.value;

        this.setState(prevState => ({
            dataProduto: {
                ...prevState.dataProduto,
                descricao: descricao
            }
        }));
    }

    onChangeFoto(e) {
        const foto = e.target.value;

        this.setState(prevState => ({
            dataProduto: {
                ...prevState.dataProduto,
                foto: foto
            }
        }));
    }

    onChangeGenero(e) {
        const generoId = e.target.value;

        this.setState(prevState => ({
            dataProduto: {
                ...prevState.dataProduto,
                generoId: generoId
            }
        }));
    }

    getTutorial(id) {
        FilmesDataService.get(id)
            .then(response => {
                this.setState({
                    dataProduto: response.data
                });
                console.log(response.data);
            })
            .catch(e => {
                alert(e);
            });
    }

    updateTutorial() {
        FilmesDataService.update(this.state.dataProduto.id, this.state.dataProduto)
            .then(response => {
                console.log(response.data);
                this.setState({
                    message: "Alterado com Sucesso!"
                });
            })
            .catch(e => {
                console.log(e);
            });
    }

    deleteTutorial() {
        FilmesDataService.delete(this.state.dataProduto.id)
            .then(response => {
                console.log(response.data);
                this.props.history.push("/user");
            })
            .catch(e => {
                console.log(e);
            });
    }

    render() {
        const { dataProduto } = this.state;

        return (
            <div>
                <div className="edit-form">
                    <h4>Tutorial</h4>
                    <form>
                        <div className="form-group">
                            <label htmlFor="title">Title</label>
                            <input
                                type="text"
                                className="form-control"
                                value={dataProduto.titulo}
                                onChange={this.onChangeTitle}
                            />
                        </div>
                        <div className="form-group">
                            <label htmlFor="description">Description</label>
                            <input
                                type="text"
                                className="form-control"
                                value={dataProduto.descricao}
                                onChange={this.onChangeDescription}
                            />
                        </div>

                        <div className="form-group">
                            <label htmlFor="description">Foto</label>
                            <input
                                type="text"
                                className="form-control"
                                value={dataProduto.foto}
                                onChange={this.onChangeFoto}
                            />
                        </div>

                        <div class="form-group">
                            <label for="inputState">Género</label>
                            <select id="inputState" class="form-control" onChange={this.onChangeGenero}>
                                <option selected value={dataProduto.generoId}>
                                    {dataProduto.genero.name}
                                </option>
                                <option value="1">Drama</option>
                                <option value="2">Comédia</option>
                            </select>
                        </div>
                    </form>

                    <button className="badge badge-danger mr-2" onClick={this.deleteTutorial}>
                        Delete
                    </button>

                    <button type="submit" className="badge badge-success" onClick={this.updateTutorial}>
                        Update
                    </button>
                    <p>{this.state.message}</p>
                </div>
            </div>
        );
    }
}
电影。路线

import axios from "axios";
import authHeader from "./auth-header";

const API_URL = "http://localhost:8080/api/";

class FilmesDataService {
    getAll() {
        // return axios.get("/trabalho");
        return axios.get(API_URL + "filmes/list", { headers: authHeader() });
    }

    get(id) {
        return axios.get(API_URL + `filmes/single/${id}`, { headers: authHeader() });
    }
}

export default new FilmesDataService();

const { authJwt } = require("../middlewares");
const filmes = require("../controllers/filmes.controller.js");
const controller = require("../controllers/user.controller");

module.exports = app => {
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Headers", "x-access-token, Origin, Content-Type, Accept");
        next();
    });

    app.post("/api/filmes/create", [authJwt.verifyToken, authJwt.isAdmin], filmes.create);

    app.get("/api/filmes/list", filmes.findAll);

    app.get("/api/filmes/single/:id", filmes.findOne);
};
exports.findOne = (req, res) => {
    const id = req.params.id;

    Filmes.findByPk(id, { include: [Generos] })
        .then(data => {
            res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message: "Ocorreu um erro a retirar os dados do produto com id=" + id
            });
        });
};
filmes.controller.js

import axios from "axios";
import authHeader from "./auth-header";

const API_URL = "http://localhost:8080/api/";

class FilmesDataService {
    getAll() {
        // return axios.get("/trabalho");
        return axios.get(API_URL + "filmes/list", { headers: authHeader() });
    }

    get(id) {
        return axios.get(API_URL + `filmes/single/${id}`, { headers: authHeader() });
    }
}

export default new FilmesDataService();

const { authJwt } = require("../middlewares");
const filmes = require("../controllers/filmes.controller.js");
const controller = require("../controllers/user.controller");

module.exports = app => {
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Headers", "x-access-token, Origin, Content-Type, Accept");
        next();
    });

    app.post("/api/filmes/create", [authJwt.verifyToken, authJwt.isAdmin], filmes.create);

    app.get("/api/filmes/list", filmes.findAll);

    app.get("/api/filmes/single/:id", filmes.findOne);
};
exports.findOne = (req, res) => {
    const id = req.params.id;

    Filmes.findByPk(id, { include: [Generos] })
        .then(data => {
            res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message: "Ocorreu um erro a retirar os dados do produto com id=" + id
            });
        });
};
我只想在该字段中输入慷慨表的值名:

但当我尝试tu时,我得到了以下错误:

您正在尝试显示dataProduto.慷慨,它是一个对象,因此不适合以这种方式呈现:

<option selected value={dataProduto.generoId}>{dataProduto.genero}</option>
{dataProduto.慷慨}
你应该这样做

<option selected value={dataProduto.generoId}>{dataProduto.genero.name}</option>
{dataProduto.genro.name}

我认为这是错误的。您正在选项子对象中使用对象,因此它不是 作为子对象有效。 或者,您应该更改为:

<option selected value={dataProduto.genero.id}>{dataProduto.genero['id' or 'name']}</option>
{dataProduto.慷慨['id'或'name']}

它应该可以工作。

看起来像是
dataProduto.grando
可能不是你所期望的那样。你是否记录了它的值以查看它是什么?dataProduto.Grando确实是一个对象(从你发布的响应正文的屏幕截图中读取),当我编写dataProduto.Grando.name时,我得到了以下错误:i.imgur.com/scRkH2e.pngGot此错误:当我这样做时!对于您的帮助,该错误确实是正确的,因为在组件生命周期的开始,或者缺少“慷慨”属性,该值将是未定义的。你必须处理这种情况,你可以做一个dataProduto.grano?dataProduto.grano.name:“No name”不幸的是,它不起作用,我得到了这个错误:您可以检查未定义的
dataProduto?.grano?.name
dataProduto.grano?dataProduto.genero.name:'--'
dataProduto?.genero?.name有效!=)泰