最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React: Loop through array of strings - Stack Overflow

programmeradmin0浏览0评论

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

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 a bit new to reactJs, I have an array of notes I want to display in the ponent;

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!

Share Improve this question edited Sep 23, 2018 at 22:24 Jeff Adam asked Sep 23, 2018 at 22:18 Jeff AdamJeff Adam 1031 gold badge1 silver badge11 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 7

I'm not sure exactly how you're planning on getting your data to your ponent but this example is how you could do it via the state. If you're having a specific ponent 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'));
发布评论

评论列表(0)

  1. 暂无评论