Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

javascript - Referencing local variable without `this` in function component

I want to refer to the variable in the function component, I think normally I use this to refer to the local variable.

However, in the function component, I can't use this.

Maybe, I am still confused by the function component though...

export default function TrackPage(props) {
    const classes = useStyles();

    useEffect(() => {
       var playlist = 1;
    }
    function handleToolBarClick(){
        this.playlist // this is empty.
    }
}
question from:https://stackoverflow.com/questions/65948626/referencing-local-variable-without-this-in-function-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Javascript scope is strictly function based. Once a variable is not in your scope it is impossible for you to access it. Therefore you need to make the variable part of your scope:

export default function TrackPage(props) {
    const classes = useStyles();

    var playlist; // Make this variable available to both 
                  // useEffect and handleToolBarClick

    useEffect(() => {
       playlist = 1;
    },[]);

    function handleToolBarClick(){
        playlist // this works
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...