首页 > 解决方案 > 按 Id 显示 React 属性

问题描述

我有多个项目,我无法通过 ID 显示每个项目页面中的每个属性。(使用 Nodejs、Reactjs、MongoDB ......)它给出了一个错误

模型“项目”的路径“_id”处的值“:id”转换为 ObjectId 失败

这个 console.log :

console.log('-----------PROJECTS byId-----------', projects);

给我undefined

我的路线:

const express = require('express'),
Projects = require('../models/projects.js'),
app = express.Router();
exports.render_projects_byId = (req, res) => {
let id = req.params.id;

Projects.findById(id).exec((err, projects) => {
    if (err) {
        console.log(err);
    }
    console.log('-----------PROJECTS byId-----------', projects);
    res.json(projects)
  });
};

我的项目页面将通过它自己的 ID 显示项目属性

import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';

import './Project.css';



class Project extends Component {
    state = {
     title : '',
     typeOfProduction: ''
    };

componentDidMount() {

    fetch('/dashboard/projects/:id')
    .then(response => { return response.json()
        .then(projects => {
            console.log(projects);
            this.setState({
                title: this.state.title,
                typeOfProduction: this.state.typeOfProduction
            })      
        })
    }).catch(error => console.error('Error:', error));
}

render() {
 console.log("This.state.projects " + this.state.projects);

    return (

        <div>
            <section className="Project container">
                  <h1>
                  {this.state.title} oi
                  </h1>
                  <h1>
                  {this.state.typeOfProduction} oi
                  </h1>
            </section>
        </div>
    );

    }
}

export default Project;

我的项目模型架构:

var mongoose = require("mongoose");

var projectSchema = new mongoose.Schema({

   title: String,
   typeOfProduction: String
})

module.exports = mongoose.model("Projects", projectSchema);

标签: node.jsreactjsmongodbfetch

解决方案


发现我的问题

我没有以正确的方式访问对象及其获取时的 ID。

    console.log("PROPS " + JSON.stringify(this.props));

道具

{"match":{"path":"/project/:id","url":"/project/5ba945d25589902362b54469","isExact":true,"params":{"id":"5ba945d25589902362b54469"}}, "location":{"pathname":"/project/5ba945d25589902362b54469","search":"","hash":""},"history":{"length":50,"action":"PUSH", “位置”:{“路径名”:“/project/5ba945d25589902362b54469”,“搜索”:“”,“哈希”:“”}}}

然后我必须像这样访问对象参数:

 const { match: { params } } = this.props;

然后我知道我正在访问路由项目:id 错误的方式

//前

获取(/dashboard/project/:id

//后

获取(/dashboard/project/${params.id}


class Project extends Component {
constructor(props){
    super(props);
    this.state = {
      project: {}
    };
}


componentDidMount() { 

console.log("PROPS " + JSON.stringify(this.props));

    const { match: { params } } = this.props;


    fetch(`/dashboard/project/${params.id}`)
    .then(response => {  return response.json()
    }).then(project => {
        this.setState({
            project: project
        })
    })
}

render() {

    return (

        <div>
            <section className="Project container">
                  <h1>
                  {this.state.project.title} oi
                  </h1>
                  <h1>
                  {this.state.project.typeOfProduction} oi
                  </h1>
            </section>
        </div>
    );

 }
}

export default Project;

推荐阅读