【问题标题】:Can't map array from mongoose in React无法从 React 中的猫鼬映射数组
【发布时间】:2020-08-03 15:19:51
【问题描述】:

我想映射一个 mongoose Schema 上的数组: (数据注释)

const {Schema, model} = require("mongoose");

const noteSchema= new Schema({
    idNote: {type: String, required: true, unique: true},
    dataNotes: [{
        title: {type:String, isRequired: true},
        authors: [{type: String, fecha: Date}] }]

}, {timestamps:true});

module.exports = model("noteSchema", noteSchema);

我从后端响应数据:

noteCtrl.getNoteInfo = async (req, res) => {
    await noteSchema.findOne({idNota: req.body.id})
        .then((response)=>{
            console.log(response)
            res.send(response);
        })
    console.log(req.body)

}

这里的数据被很好地发送,作为一个对象

我的前端有:

    ObtNofNotes = async () => {
        await axios.post("http://localhost:4000/api/users/notes", {
            id:
                JSON.parse(localStorage.getItem("user")).user
        })
            .then((res) => {
                console.log("Notes data " + res.data.dataNotes)
                //It only returns [object Object] for each array
                return this.notesArray(res.data.dataNotes)
            })
            .catch((err) => console.log(err));
    }

    notesArray= (n) => {
        n.map(nm => {
            console.log(nm)
            //it returns the arrays just fine
            return (<li>{nm.dataNotes[0][0]}</li>)
        })
    }

但是当我想渲染 li 时:

render() {
        return (
            <div>
                {this.ObtNofNotes()}
            </div>
        )
    }

React 返回错误:“对象作为 React 子级无效(找到:[object Promise])。如果您要渲染子级集合,请改用数组。”

但是数据已经在一个数组中,当我在 n.map() 函数中使用 console.log(nm) 时,它会返回每个数组和其中的对象。

我做错了什么?

我认为它与异步函数和承诺有关,因为它渲染 this.ObtNofNotes(),一个异步函数,我不确定它是否在渲染之前有数据,或者它是否在之前等待数据渲染,但我不确定。我是 React 新手,非常感谢您的帮助!

【问题讨论】:

    标签: javascript node.js reactjs mongodb mongoose


    【解决方案1】:

    在调用 .then() 之前,在 findOne 查询函数之后传入 .lean()

    【讨论】:

      【解决方案2】:

      我解决了! 我这样做了:

      我在组件状态下创建了一个数组:

      state = {
         notes: []
      }
      

      然后在获取notes的函数中,将notes数据推送到notes状态:

      .then((res) => {
         this.setState({notes: res.data.dataNotes})
      })
      

      然后,在 componentDidMount 函数中,我调用了从后端接收数据的异步函数:

      componentDidMount(){
              this.ObtNofNotes();
      }
      

      然后在渲染函数中,我映射从状态调用它的notes数组,并映射它:

      render() {
      
              return (
                  <div>
                      {
                      this.state.notes.map(Data=>(
                      <div>
                          <Note data= 
                              {Data}>
                          </Note>
                      </div>
                      ))}
                  </div>
              )
          }
      

      希望这对其他人有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-28
        • 2017-06-01
        • 2017-07-23
        • 1970-01-01
        • 2021-08-08
        • 2016-06-29
        • 2015-07-01
        相关资源
        最近更新 更多