我正在构建一个自动生成恒星的太阳系应用程序。我的star
是一个接受几个道具的React组件。当用户单击星号时,我需要更新system
状态,并且我希望navlink
指向相同的值。
let randomTypeVariable = starList[Math.floor(Math.random() * 6 + 1)];
return (
<NavLink
to={`/${randomTypeVariable}`}
onClick={() => props.setSystem(`${randomTypeVariable}`)}
className="starWrapper"
>
然而,目前to=
道具和onClick
函数给出了不同的结果。我知道这是因为randomTypeVariable
每次都在运行,并给出不同的结果。
这些组件是随机生成的,因此我不能将变量设为常数值。如何将这两个属性分配为同一个随机生成的变量?
对于上下文,这里是完整的star
组件
let randomTypeVariable = starList[Math.floor(Math.random() * 6 + 1)];
const makeStars = (Count = 5) => {
if (Count > 0) {
return (
<NavLink
to={`/${randomTypeVariable}`}
onClick={() => props.setSystem(`${randomTypeVariable}`)}
className="starWrapper"
>
<Star
starName={`${makeStarName()}`}
starPosition={positionList[Math.floor(Math.random() * 9 + 1)]}
starType={`${starList[Math.floor(Math.random() * 6 + 2)]}`}
></Star>
{makeStars(Count - 1)}
</NavLink>
);
}
};
它不应该给出不同的结果,因为randomTypeVariable
不是一个函数,我也尝试过。
也许我错过了什么,但useMemo
仍然可以解决你的问题
const makeStars = (Count = 5) => {
let randomTypeVariable = useMemo(() => starList[Math.floor(Math.random() * 6 + 1)], []);
if (Count > 0) {
return (
<NavLink
to={`/${randomTypeVariable}`}
onClick={() => props.setSystem(`${randomTypeVariable}`)}
className="starWrapper"
>
<Star
starName={`${makeStarName()}`}
starPosition={positionList[Math.floor(Math.random() * 9 + 1)]}
starType={`${starList[Math.floor(Math.random() * 6 + 2)]}`}
></Star>
{makeStars(Count - 1)}
</NavLink>
);
}
};
所以我没能解决这个问题。我做的第一件事是从我的组件中删除onClick
let randomTypeVariable = starList[Math.floor(Math.random() * 6 + 1)];
if (Count > 0) {
return (
<NavLink
to={`/${randomTypeVariable}`}
className="starWrapper"
>
<Star
starName={`${makeStarName()}`}
starPosition={positionList[Math.floor(Math.random() * 9 + 1)]}
starType={`${randomTypeVariable}`}
></Star>
{makeStars(Count - 1)}
</NavLink>
考虑到我仍然能够使用to={/${randomTypeVariable}}
的导航路径,我能够从页面的URL而不是状态中收集我需要的信息。
let url = window.location.href
let modifiedUrl = url.split('/')
props.setSystem(modifiedUrl[3])
最后,随机生成的分量是一致的。然而,这更多的是为了避免问题,而不是实际解决问题。如果有人有实际的解决方案,请在这里听到你的声音。