简体   繁体   中英

How to re-render a react component after returning something in a function?

I'm creating a react app with a method to draw some arrows among divs. The function doesn't produce arrows right away returns the JSX but just after I manually re-render the DOM by scrolling the page or do a route change . How can I force render the DOM after the return of the function?

drawArrows = () => {
        const questionsList = this.state.questionsData;
        return questionsList.map(each =>
            <Arrow
                key={each.order}
                fromSelector={`#option${each.order}`}
                fromSide={'right'}
                toSelector={`#q${each.order}`}
                toSide={'left'}
                color={'#ff6b00'}
                stroke={3}
            />
        );
    }

render (){
    return(
       ...code
       {this.drawArrows()}
    )
}

you can do it easy with functional Component with useState and useEffect

import { useState } from 'react';
const ComponentName = () => {
const [arow, setArow] = useState();
const [questionsData, setQuestionsData] = useState([]);
const drawArrows = () => questionsData.map(each =>
    <Arrow
        key={each.order}
        fromSelector={`#option${each.order}`}
        fromSide={'right'}
        toSelector={`#q${each.order}`}
        toSide={'left'}
        color={'#ff6b00'}
        stroke={3}
    />
);
useEffect(() => {
    setArow(drawArrows())
}, [])
return (
    { arow }
)

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM