【问题标题】:display an array with the largest number of votes显示投票数最多的数组
【发布时间】:2021-12-09 13:42:22
【问题描述】:

我目前在 FullStackOpen 上有一门 Introduction to React 课程,但我被困在 1.14 anecdotes exercise 中,这需要应用程序使用票数最多。浏览器可以渲染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

【问题讨论】:

  • 你的问题是vote.indexOf(Mostvote):在这段代码中,Mostvote 是一个函数,你试图在vote 数组中找到该函数的索引,它不会' t find as vote 是一个数字数组。由于indexOfvote 数组中找不到Mostvote 函数,您将获得-1 的索引。相反,您需要在 vote 数组中查找最大数字的索引。您在尝试将 bestAnecdote 用作组件时还有其他问题:&lt;bestAnecdote anecdotes ={...} /&gt;,bestAnecdote 不是组件,它是您的轶事数组(或 undefined)中的字符串
  • 非常感谢尼克的建议!确实很有帮助:)

标签: javascript arrays reactjs react-hooks indexof


【解决方案1】:

问题

  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} />

完整代码:

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>
  );
};

【讨论】:

  • 感谢您提出问题和可能的解决方案!他们确实非常有帮助!我还发现浏览器无法呈现BestAnecdote 数组,因为第一个字母表以前是小写字母!设法修复 Bestvote 如下:const App = () =&gt; { const BestAnecdote = () =&gt; ( &lt;p&gt;{anecdotes[vote.indexOf(Math.max(...vote))]}&lt;/p&gt; ) return ( &lt;&gt; &lt;BestAnecdote anecdotes = {BestAnecdote}/&gt; &lt;/&gt; ) }
【解决方案2】:

尼克解决了大部分问题。这是一个工作版本,您可以使用它来查看问题所在:

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 = (props) => {
  return <h4>{props.anecdotes}</h4>
}

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>
  )
  
  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(Math.max(...vote))]}/>
      <Mostvote vote = {Mostvote}/>
    </div>
  )
}

export default App

【讨论】:

  • 非常感谢约瑟夫的建议,它有效!
猜你喜欢
  • 2022-08-05
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
相关资源
最近更新 更多