简体   繁体   中英

React: Loop through array of strings

I'm a bit new to reactJs, I have an array of notes I want to display in the component;

data: {
    title: 'notes for ABC', 
    notes: ['hello', 'world', 'blah blah]
}

When I try rendering this as data.notes.map it said data.notes.map is not a function. Any help!

I'm not sure exactly how you're planning on getting your data to your component but this example is how you could do it via the state. If you're having a specific component rendering a post or note, it would be better to do it via props. I would read the List and Keys docs for React.

Class Style

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

class App extends Component {
  constructor(props) {
    super(props); 
    this.state = { 
      notes: ['hello', 'world', 'blah blah'] 
    };
  }

  render() {
    const noteItems = this.state.notes.map((note) =>
      <li>{note}</li>
    );
    return (
      <ul>{noteItems}</ul>
    );
  }
}

export default App;

ReactDOM.render(<App />, document.getElementById('root'));

Functional Style

It seems like the functional way of writing this is more preferred, this is how you would write that.

import React, { useState } from 'react';

function App() {
  const [notes, setNotes] = useState(['hello', 'world', 'blah blah'])
  return <ul>{notes.map((note) => <li>{note}</li>)}</ul>
}

export default App;

ReactDOM.render(<App />, document.getElementById('root'));

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