我正在参加FullStackOpen的React入门课程
,卡在1.14轶事练习
中,要求应用程序显示投票最多的轶事。 浏览器能够呈现Mostvote数组
,它呈现了最高投票的轶事的得票数,但无论我怎么做,都无法显示最高投票(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
数组中查找该函数的索引,但是由于vote
是一个数字数组,所以它无法找到。由于indexOf
在vote
数组中找不到Mostvote
函数,因此你会得到一个-1
的索引值。相反,你需要查找vote
数组中最大数字的索引。此外,你还有其他问题,试图将bestAnecdote
作为组件使用:<bestAnecdote anecdotes ={...} />
,但是bestAnecdote
不是一个组件,它是来自你的轶事数组的字符串(或undefined
)。 - Nick Parsons