How to display a range of indices in a reaction?

<table>
   <tbody>
   {this.state.data.map((person, i) => <TableRow key = {i} data = {person} />)}
   </tbody>
</table>

This displays my entire array, but how do I display from the minimum index to the maximum index? So to speak, my array has 500 elements. I want to display this array of (data) from index 15 to 24 inclusive. (Thus, I had only 10 elements on the screen).

edit: these answers are interesting .. but not mentioned .filter () though? I saw that this can help what I want, but I'm trying to figure out how to do this in a reaction.

+4
source share
3 answers

Use Array#slice()to extract a shallow copy of the values ​​from this.state.data.

const SubsetTable = props => {
  let {startIndex, endIndex, data} = props

  let subset = data.slice(startIndex, endIndex)

  return (
   <table>
     <tbody>
       {subset.map((person, i) => (<TableRow key = {i} data = {person} />)}
     </tbody>
   </table>
  )
}

// Since splice() is inclusive of the range given, you'll need to 
// adjust your range to include that last index if needed
// The below will grab all values in indexes 15-24, 
<SubsetTable startIndex={15} endIndex={25} data={this.state.data} />

, Array#filter(), filter() , . Array#slice() , . filter() , , , Array , .

+4

, Array.prototype.map .
.

, Array.prototype.reduce, , .

:

const persons = [
  { value: 'John', id: 1 },
  { value: 'Jane', id: 2 },
  { value: 'Mike', id: 3 },
  { value: 'Nikol', id: 4 },
  { value: 'Bob', id: 5 },
  { value: 'Dave', id: 6 },
]

const TableRow = ({ data }) => <tr><td>{data.value}</td></tr>

const start = 2;
const end = 4;

const App = () => (
  <div >
    <table>
      <tbody>
        {
          persons.reduce((result, current, i) => {
            if (i >= start && i <= end) { // 0 based don't forget!
              const row = (<TableRow key={i} data={current} />);
              result.push(row);
            }
            return result;
          }, [])
        }
      </tbody>
    </table>
  </div>
);

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Hide result
+1

min/max ( )

this.state = {
    min: 15,
    max: 24,
};

if, , (i) min max.

{this.state.data.map((person, i) => {
    if (i >= this.state.min && i <= this.state.max) {
        return (<TableRow key = {i} data = {person} />);
    }
})}

Now we can be real and say that it is inefficient. So, after you have reached the maximum, exit the cycle, which may require a different type of cycle, since I think you cannot break withmap

0
source

Source: https://habr.com/ru/post/1693281/


All Articles