简体   繁体   中英

Fetching data from function into <View> component inside the render method

I tried to fetch the data from function inside render, when I use alert() it works, but when I try to return real text it not shown any thing

the code I work with:

export default class App extends Component {
    renderResualts(){
        db.find({}, function (err, docs) {
           return docs.map(function(d){
              return(
                <Text>{d.name}</Text>
              )
           })
        })
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResualts() }
      </View>
    );
  }
}

-- UPDATED CODE:



export default class App extends Component {

    constructor(props){
        super(props)
        this.state = {graves:[]}
    }
    componentDidMount(){
        db.find({}, function (err, docs) {
            this.setState({graves:docs})
        })       
    }

    renderResults(){
        return this.state.graves.map(grave =>
            <Text>{grave.name}</Text>    
        )
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResults() }
      </View>
    );
  }
}

It should be shown these data :

{ _id: 1, name: 'Parturient', year: 2017 }, { _id: 2, name: 'Dapibus', year: 2017 }

inside text like so: ParturientDapibus

try this

renderResults(){
    return (
       <View>
           this.state.graves.map(grave =>
                <Text>{grave.name}</Text>    
           )
      </View>
    );
}

By passing the data to State like so:


export default class App extends Component {

    constructor(props){
        super(props)
        this.state = {graves:[]}
    }
    componentDidMount(){
        db.find({}, (err, docs)=> {
            this.setState({graves:docs})
        })       
    }

    renderResults(){
        return this.state.graves.map(grave =>
            <Text key={grave._id}>{grave.name}</Text>    
        )
    }
  render() {
    return (
      <View style={styles.container}>
          { this.renderResults() }
      </View>
    );
  }
}

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