使用随机性
在 Remotion 中,以下做法是一种反模式:
🌐 The following thing is an anti-pattern in Remotion:
const MyComp : React .FC = () => {
const [randomValues ] = useState (() =>
new Array (10).fill (true).map ((a , i ) => {
return {
x : Math .random (),
y : Math .random (),
};
}),
);
// Do something with coordinates
return <></>;
};虽然这在预览时可以工作,但在渲染时会出错。原因是 Remotion 会启动多个网页实例以并行渲染帧,而随机值在每个实例上都会不同。
🌐 While this will work during preview, it will break while rendering. The reason is that Remotion is spinning up multiple instances of the webpage to render frames in parallel, and the random values will be different on every instance.
解决问题
🌐 Fixing the problem
使用 Remotion 的 random() API 来获取确定性的伪随机值。传入一个种子(数字或字符串),只要种子相同,返回值就会相同。
🌐 Use the random() API from Remotion to get deterministic pseudorandom values. Pass in a seed (number or string) and as long as the seed is the same, the return value will be the same.
import { random } from "remotion";
const MyComp : React .FC = () => {
// No need to use useState
const randomValues = new Array (10).fill (true).map ((a , i ) => {
return {
x : random (`x-${i }`),
y : random (`y-${i }`),
};
});
return <></>;
};现在所有线程上的随机值将相同。
🌐 Now the random values will be the same on all threads.
假阳性
🌐 False positives
当使用 Math.random() 时,你是否收到了 ESLint 警告,但你完全清楚上述情况?使用 random(null) 可以在不触发警告的情况下获取真正的随机值。
🌐 Did you get an ESLint warning when using Math.random(), but you are fully aware of the circumstances described above? Use random(null) to get a true random value without getting a warning.
异常:在 calculateMetadata() 内
🌐 Exception: Inside calculateMetadata()
在 calculateMetadata() 内使用真正的随机值是安全的,因为它只被调用一次,并且不会并行执行。
🌐 It is safe to use true random values inside calculateMetadata(), as it is only called once and not in parallel.
另请参阅
🌐 See also