javascript - 显示投票数最多的数组

标签 javascript arrays reactjs react-hooks indexof

我目前正在 FullStackOpen 上一门 React 简介 类(class),我被困在 1.14 轶事练习,要求应用程序显示得票最多的轶事。浏览器能够呈现 Mostvote Array,它呈现投票最多的轶事的投票,但投票最多的 (bestAnecdote ) 无论我做什么都无法显示轶事。有谁知道我哪里做错了吗?提前谢谢你 :) 下面我附上了我的 React 代码:

import React, { useState } from 'react'

const Header = (props) => {
  return <h1>{props.contents}</h1>
}

const Button = (props) => (
  <button onClick={props.handleClick}>
    {props.text}
  </button>
) 

const Vote = ({vote}) => (
<p>has {vote} votes</p>
)

const App = () => {

  const contents = {
      text1: "Anecdote of the day",
      text2: "Anecdote with most votes"
  }

  const anecdotes = [
    'If it hurts, do it more often',
    'Adding manpower to a late software project makes it later!',
    'The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
    'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
    'Premature optimization is the root of all evil.',
    'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.',
    'Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients'
  ]

  const random = () => (
    Math.floor(Math.random() * 7)
  )

  const [selected, setSelected] = useState(0)
  const [vote, setVote] = useState(new Array(anecdotes.length).fill(0))

  const Anecdotevoting = () => {
    const copy = [...vote];
      copy[selected] += 1;
      setVote(copy);
  }
  
  const Mostvote = () => (
    <p>has {Math.max(...vote)} votes</p>
  )

  const bestAnecdote = anecdotes[vote.indexOf(Mostvote)];
  
  console.log(bestAnecdote)
  return (
    <div>
      <Header contents = {contents.text1}/>
      {anecdotes[selected]}<br/>
      <Vote vote = {vote[selected]}></Vote>
      <Button handleClick={Anecdotevoting} text = 'vote'/>
      <Button handleClick={() => setSelected(random)} text = 'next anecdote'/>
      <Header contents = {contents.text2}/>
      <bestAnecdote anecdotes = {anecdotes[vote.indexOf(Mostvote)]}/>
      <Mostvote vote = {Mostvote}/>
    </div>
  )
}

export default App

最佳答案

问题

  1. 您正在使用 copy[selected] += 1; 改变 Anecdotevoting 中的状态。即使您浅复制了 vote 状态,元素仍然引用原始元素。
  2. MostVote 值为 JSX,因此 anecdotes[vote.indexOf(Mostvote)]; 将始终为 -1

解决方案

更新 anecdoteVoting 处理程序以不改变状态。您可以将前一个状态映射到下一个状态,当映射索引与所选索引匹配时返回一个新值,否则返回当前值。

const anecdoteVoting = () => {
  setVote((votes) => votes.map((vote, i) => vote + (i === selected ? 1 : 0)));
};

同时计算一个mostVotes索引。

const { mostVotes, index } = vote.reduce(
  (mostVotes, curr, index) => {
    if (curr > mostVotes.mostVotes) {
      return { mostVotes: curr, index };
    }
    return mostVotes;
  },
  { mostVotes: Number.NEGATIVE_INFINITY, index: -1 }
);

...

<BestAnecdote anecdote={anecdotes[index]} />
<Vote vote={mostVotes} />

Edit display-an-array-with-the-largest-number-of-votes

完整代码:

import React, { useState } from "react";

const Header = (props) => {
  return <h1>{props.contents}</h1>;
};

const Button = (props) => (
  <button onClick={props.handleClick}>{props.text}</button>
);

const Vote = ({ vote }) => <p>has {vote} votes</p>;

const BestAnecdote = ({ anecdote }) => <p>{anecdote}</p>;

const contents = {
  text1: "Anecdote of the day",
  text2: "Anecdote with most votes"
};

const anecdotes = [
  "If it hurts, do it more often",
  "Adding manpower to a late software project makes it later!",
  "The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.",
  "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.",
  "Premature optimization is the root of all evil.",
  "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
  "Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients"
];

const random = () => Math.floor(Math.random() * anecdotes.length);

const App = () => {
  const [selected, setSelected] = useState(0);
  const [vote, setVote] = useState(new Array(anecdotes.length).fill(0));

  const anecdoteVoting = () => {
    setVote((votes) => votes.map((vote, i) => vote + (i === selected ? 1 : 0)));
  };

  const { mostVotes, index } = vote.reduce(
    (mostVotes, curr, index) => {
      if (curr > mostVotes.mostVotes) {
        return { mostVotes: curr, index };
      }
      return mostVotes;
    },
    { mostVotes: Number.NEGATIVE_INFINITY, index: -1 }
  );

  return (
    <div>
      <Header contents={contents.text1} />
      {anecdotes[selected]}
      <br />
      <Vote vote={vote[selected]}></Vote>
      <Button handleClick={anecdoteVoting} text="vote" />
      <Button handleClick={() => setSelected(random)} text="next anecdote" />
      <Header contents={contents.text2} />
      <BestAnecdote anecdote={anecdotes[index]} />
      <Vote vote={mostVotes} />
    </div>
  );
};

关于javascript - 显示投票数最多的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69684889/

相关文章:

node.js - 将 JSON 数组解析为 JSON 对象时出错

javascript - React 映射嵌套数据

javascript - React - 将项目添加到特定索引处的状态数组中

javascript - jQuery 函数 $.post 和 .remove

javascript - 如何仅解析选定类的ul标签数据

java - 想要将 org.bytedeco.javacpp.lept.PIX 转换为 byte[] 和缓冲图像

Javascript 根据 if 语句更改 array[i],然后在每次运行函数时将其连接起来

javascript - 在 react js 中搜索一个好年选择器下拉包。我试过 react-year-picker 但图书馆有一些错误

javascript - 检测 AJAX 调用循环何时完成

javascript - Bower:找不到适合 Angular 的版本