我有一个称为样式的函数,该函数在其中检查参数值以返回Card组件的颜色,一个朋友告诉我尝试使用useMemo
仅在参数更改时运行该函数,但是我可以没有找到一种方法来理解这个问题。我如何通过不需要运行该功能的条件?
function styling(votes) {
let styling = '#696969'
if (votes > 0) {
styling = '#008000'
} else if (votes < 0) {
styling = '#B22222'
}
return styling
}
function App() {
const [content,setContent] = useState(images)
const upVote = (param) => {
setContent(() => {
for(let i = 0; i < content.length; i++) {
if (content[i].id === param){
content[i].votes = content[i].votes+1
}
}
return [...content]
})
}
const downVote = (param) => {
setContent(() => {
for(let i = 0; i < content.length; i++) {
if (content[i].id === param){
content[i].votes = content[i].votes-1
}
}
return [...content]
})
}
return (
<div classname="App">
<div classname="grid">
{content.map((picture,index) => {
return <Card key={index} picture={picture} upVote={upVote} downVote={downVote} style={styling(picture.votes)}/>
})
}
</div>
</div>
)
}
export default App