使用React animated/useSpring报错​Got NaN while animating的解决方法

使用 React 的 <animated.div /> 时,发现控制台一直打印报错/报警:Got NaN while animating: SpringValue {id: 2899, key: 'width', _priority: 0, animation: Animation, queue: undefined, …} 。

这说明页面中有使用数学运算,并且在计算中传递了非整数值 NaN ,这样表达式会返回 NaN ,造成报错。

报错代码示例:

import { useSpring, animated, config } from 'react-spring';

const Index: React.FC<{
  value: number;
  minValue: number;
  maxValue: number;
  maxWidth: number;
  index: number;
  barColor: string;
}> = (props) => {
  const { value, minValue, maxValue, maxWidth, index, barColor } = props;
  const barWidth = ((value - minValue) / (maxValue - minValue)) * maxWidth;
  const springProps = useSpring({
    from: { opacity: 1, width: 0, height: '100%', background: barColor },
    to: { opacity: 1, width: barWidth, height: '100%', background: barColor },
    delay: 4,
    config: config.default,
  });

  return (
    <div
      style={{
        height: '100%',
        borderRadius: 2,
      }}
    >
        <animated.div style={springProps} />
    </div>
  );
};

export default PerCentBar;

这里的 barWidth 变量可能会出现空值,给它一个默认值 0 即可。

解决方法:

12 行改为:

const barWidth = ((value - minValue) / (maxValue - minValue)) * maxWidth || 0;


未经允许不得转载:Web前端开发资源网 » 使用React animated/useSpring报错​Got NaN while animating的解决方法

推荐阅读:

使用flexible后 不同设备的data-dpr还始终为1解决方法

phpsStorm实现打开*.jsp文件代码高亮和代码格式化

20180410博客更换服务器步骤

PHP连接MySQL数据库报错:Call to undefined function mysql_connect()的解决方法

input[type=file]去掉“未选择任何文件”及样式改进

赞 (0)
分享到: +

评论 沙发

换个身份

  • 昵称 (必填)
  • 邮箱 (选填)