简体   繁体   中英

Use variable outside of map function with react

I'm having a little problem with some vars.

My code is:

import React from 'react';
import mongoose from 'mongoose';
var sch = require('../models/schema');

export default class IndexPage extends React.Component {
  render() {

    sch.find(function(err,models){
       //???
    });

    return (
      <div className="home">
        Afiez ceva {models}
      </div>
    );

  }
}

How to achieve this? I ve tried all the posibilites. I want to be able to render someting like {models} or {models[0].whatever} .. Some tip please?

Reference for sch:

import mongoose from 'mongoose';

var schValue = new mongoose.Schema({
  asd: String
});

schValue.set( 'collection', 'ecommerce' );

module.exports = mongoose.model('sch', schValue);

I have not tested it but is that something like this you need :

  export default class IndexPage extends React.Component {

  constructor() {
    super();

    this.state = {
      models: [],
    };
  }

  componentWillMount() {
    sch.find({}, (err, models) => {
      this.setState({ models });
    });
  }

  render() {
    return (
      <div className="home">
        {this.state.models.map(model => {
          return model;
        })}
      </div>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM