【发布时间】: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 asvote是一个数字数组。由于indexOf在vote数组中找不到Mostvote函数,您将获得-1的索引。相反,您需要在vote数组中查找最大数字的索引。您在尝试将bestAnecdote用作组件时还有其他问题:<bestAnecdote anecdotes ={...} />,bestAnecdote 不是组件,它是您的轶事数组(或undefined)中的字符串 -
非常感谢尼克的建议!确实很有帮助:)
标签: javascript arrays reactjs react-hooks indexof