I
I
Ivan Shulga2020-07-06 20:04:43
React
Ivan Shulga, 2020-07-06 20:04:43

Why is it endlessly redrawn and how to do it right?

(React Hooks)
The graph is drawn through the data that is in the editor, if I delete an element in this data through the action, then an endless redrawing starts, what's the problem?

const Chart = React.memo((props) => {
    const [data, setData] = useState(props.items.map((elem) => {
        return elem.weight
    }))
    const svgRef = useRef()

    useEffect(() => {

        setData(props.items.map((elem) => {
            return elem.weight
        }))
        const svg = select(svgRef.current)

        const xScale = scaleLinear()
            .domain([0, data.length - 1])
            .range([0, 1240])

        const yScale = scaleLinear()
            .domain([min(data), max(data)])
            .range([280, 0])
        const myLine = line()
            .x((value, index) => xScale(index))
            .y(value => yScale(value))
            .curve(curveCardinal)
        svg
            .selectAll('path')
            .data([data])
            .join('path')
            .attr('d', value => myLine(value))
            .attr('fill', 'none')
            .attr('stroke', 'lavender')
            .attr('stroke-width', '3px')
            .attr('width', '100%')
    }, [data, props.items])

    return (
        <div className={s.elem}>
            <svg viewBox={'0 -9 1240 300'}
                ref={svgRef}></svg>
        </div>
    )
})

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
hzzzzl, 2020-07-06
@ZamarShoo

useEffect(() => {

        setData(props.items.map((elem) => {   // setData
            return elem.weight
        }))

      } , [data, props.items] })    // data?

here the effect listens to data changes, and you change data in it, thereby restarting it ..
and why store data in the state at all, instead of directly using props.items from the store?

I
Ivan Shulga, 2020-07-06
@ZamarShoo

I put it wrong: I tried to pull out setData and remove it (which seemed logical to me from the very beginning), because it monitors changes in props.items, but if the props changes, then how to overwrite data?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question