我有一个产生随机颜色的函数。每次单击按钮时,我都想采用这种随机颜色。我尝试设置颜色 **setBgColor(random_bg_color())** 但它给出了这样的错误。错误:超出最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 如何调用我的随机颜色函数并在钩子中设置?
import React, {useContext } from 'react';
import {GeneralContext} from "./App"
export default function Theme() {
function random_bg_color() {
var x = Math.floor(Math.random() * 120);
var y = Math.floor(Math.random() * 120);
var z = Math.floor(Math.random() * 120);
const rgb = 'rgb(' + x + ',' + y + ',' + z + ')';
return rgb;
}
const {value,value2,value3}=useContext(GeneralContext)
const [text, setText] = value;
const [author,setAuthor] = value2;
const [bgColor,setBgColor]=value3
setBgColor(random_bg_color())
return (
<div>
<p>{bgColor}</p>
<p>{author}</p>
</div>
)
}
答案 0 :(得分:2)
如果你想在组件渲染时设置一次,你可以使用 useEffect 钩子。
useEffect(() => {
setBgColor(random_bg_color());
},[])
作为 useEffect 钩子的第二个参数的空数组确保此代码在组件挂载时运行。
答案 1 :(得分:1)
创建一个处理程序并将其传递给按钮的 onClick
const handleClick = ()=>{
setBgColor(random_bg_color());
}