无法在React中从猫鼬映射数组

时间:2020-04-21 00:05:16

标签: javascript node.js reactjs mongodb mongoose

我想映射一个在猫鼬模式上的数组: (dataNotes)

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)时,它将返回每个数组以及其中的对象。

我在做什么错了?

我认为它与async函数和promises有关,因为它呈现了this.ObtNofNotes(),async函数,并且我不确定它是否在呈现之前有数据或是否在等待之前有数据渲染,但我不确定。我是React的新手,感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我解决了! 我是这样做的:

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

state = {
   notes: []
}

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

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

然后,在componentDidMount函数中,我调用了异步函数,该函数从后端获取数据:

componentDidMount(){
        this.ObtNofNotes();
}

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

render() {

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

希望这会帮助别人!