首页 > 解决方案 > 显示列表中的最高分

问题描述

我有一个数组this.state。数组的对象有 2 个键:[text] 和 [score]。

我只需要显示得分最高的对象的 [text] 键。例如

[{ text: 'foo', score: 1, }, { text: 'bar', score: 0.1, }]

这里最高分是 1,[text] 键值为“foo”。所以只需渲染“foo”。

代码:

class Score extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = 
       {
       text: [
         {
         title: 'el', 
         data: [
           {
             el: 'hello',
             score: 1
           },
           {
             el:  'hallo',
             score: 0.10
           }
         ]
         },
       ] 
       
       }
  }
  
 
            
  render() {
    return (
      <div>
      {
          this.state.text.map((q, i) => (
            <div key={i} className="card">
             
                {
                  q.data.map((i, j) => 
                    (
                    <div key={j}>
                     <p>{i.el}</p>
                     <p>{i.score}</p>
                    
                      </div>
                    )
                 )}
             
            </div>
          ))
        }
      </div>
    );
  }
}



const Root = document.getElementById("root");
ReactDOM.render(<Score />, Root);

标签: javascriptreactjs

解决方案


Array#map将显示每个元素,而不仅仅是得分最高的元素。

在地图内部,您应该删除一些逻辑,该逻辑将找到得分最高的对象并显示它。

this.state.text.map((q, i) => {
   const r = q.data.sort((a, b) => b.score - a.score)[0];
   // ^^^^^^^^^^^^^^^^^^^ sort ascending and pick the first element

   return (
      <div key={i} className="card">
         <p>{r.el}</p>
         <p>{r.score}</p>
      </div>
   );
})

const r = [{ text: 'hello', score: 1 }, { text: 'hallo', score: 0.1 }];
const res = r.sort((a, b) => b.score - a.score)[0];

console.log(res);


推荐阅读