我有一个名为styleing的函数,在这里我检查参数的值以返回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
您传递的属性可以更新数组中函数的结果,例如,像许多其他钩子一样的useMemo(() => { ... }, [propOne, propTwo])
。
在你的情况下,你会通过votes
。
style
道具需要一个对象。要让它发挥作用,你必须改变:
<Card
key={index}
picture={picture}
upVote={upVote}
downVote={downVote}
style={{
color: styling(picture.votes)
}}
/>
或者从函数中返回对象,然后直接使用,就像您已经在使用的一样。
//in parent component of App:
return <Card key={index} picture={picture} upVote={upVote} downVote={downVote} votes={picture.votes}/>
// in your child functional component votes is a prop passed in dynamically, let's memoize it to `styleBaseOnVote` to stop unnecessary re-renders.
function ChildComponent(picture: <yourPictureObjInterface>, upVote: function, downVote:function, votes: Number): ReactElement {
const styleBaseOnVote = useMemo(() => {
let styling = '#696969'
if (votes > 0) {
styling = '#008000'
} else if (votes < 0) {
styling = '#B22222'
}
return styling
}
, [votes])
return <div style={{color: styleBaseOnVote}}
}
useMemo
需要存储一个与有效CSS属性匹配的对象。下面是一个设置分区宽度和高度的示例
const MyCustomImage = (props) => {
const wrapperStyle = useMemo(() => {
return {width: props.width, height: props.height};
}, [props.width, props.height]);
return (
<div style={wrapperStyle}>
test
</div>
);
};