3

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.
    }
}
3
  • 1
    You need to store values either in state with useState (if changing it should cause a re-render), or in a ref with useRef (if you want to change the value without triggering a re-render). Commented Jan 29, 2021 at 4:08
  • Make a class component if you want this, Function components are stateless, or use hooks as Jayce mentions above, which essentially enable state to persist across render and be accessed via useState, etc. Commented Jan 29, 2021 at 4:09
  • Your useEffect function is incorrect. The usage need to be corrected. Can you please correct it. Commented Jan 29, 2021 at 4:35

1 Answer 1

3

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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. component function can declare the variable here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.