Reactjs React,Typescript,d3js,得到的No重载与此调用匹配
我发现在使用d3js中的scaleLinear()函数时,Typescript抛出了一个错误,我想知道是否有人能为我指明解决这个问题的方向。代码内置于react中,并使用typescript。以下是源代码:Reactjs React,Typescript,d3js,得到的No重载与此调用匹配,reactjs,typescript,d3.js,Reactjs,Typescript,D3.js,我发现在使用d3js中的scaleLinear()函数时,Typescript抛出了一个错误,我想知道是否有人能为我指明解决这个问题的方向。代码内置于react中,并使用typescript。以下是源代码: import React, { useRef, useState, useEffect } from 'react'; import { select, Selection } from 'd3-selection'; import { scaleLinear } from 'd3-scal
import React, { useRef, useState, useEffect } from 'react';
import { select, Selection } from 'd3-selection';
import { scaleLinear } from 'd3-scale';
const dataTest = [
{
name: 'Oct30',
number: 8000
},
{
name: 'Oct29',
number: 2000
},
{
name: 'Oct28',
number: 600
},
{
name: 'Oct27',
number: 3005
}
]
const Barchart: React.FC = () => {
const ref = useRef<SVGSVGElement | null>(null);
const [selection, setSelection] = useState< null | Selection<SVGSVGElement | null, unknown, null, undefined>>(null);
const y = scaleLinear()
.domain([0, 10000])
.range([0, 400])
useEffect(() => {
if(!selection){
setSelection(select(ref.current))
} else {
console.log("y(0) ", y(0));
console.log("y(0) ", y(2305)); // What happens as a test
// selection is where typescript is showing the error
selection
.selectAll('rect')
.data(dataTest)
.enter()
.append('rect')
.attr('width', 100)
.attr('x', (_, i) => i * 100)
.attr('fill', 'orange')
.attr('height', d => y(d.number)); // <the y() seems to be the problem.
}
}, [selection])
return (
<div>
<svg ref={ref} width={800} height={400} />
</div>
);
};
}
export default Barchart;
到
没有错误。我猜这行是“const y=scaleLinear()”,我需要设置一些内容。任何帮助都将不胜感激
进行此更改时运气不佳:
let y = scaleLinear<number>()
.domain([0, 10000])
.range([0, 400])
设y=scaleLinear()
.domain([0,10000])
.范围([0400])
问题在于scaleLinear()
在100%的时间内不会返回值。在ScaleLinear
类型的定义中,您可以看到它可以返回number
或undefined
const y: ScaleLinear
(value: NumberValue) => number | undefined
但是,当您在SVG选择上设置属性“height”时,您要设置的值必须是一个数字。它不能是未定义的
const y: ScaleLinear
(value: NumberValue) => number | undefined
修复很容易。如果y(d.number)
返回未定义的
,我们将提供一个后备编号
,用作高度。这里我使用0
.attr('height', d => y(d.number) || 0 );
.attr('height', d => y(d.number) || 0 );