简体   繁体   中英

Cannot use this.props or set this.state in function outside Render

First post and new to react.

I am having an issue whereby when I try to use a prop in a function outside the render it is undefined and when trying to use it to set a state value, it does not work.

I have read up about this and have found many answers, mainly that the all functions should be bound to the class or use the arrow method so when referring to this inside the function it refers to the class.

None of these seem to work.

Any assistance would be greatly appreciated.

Below is the code I am using.

I call the EntryForm component from another component passing the value 5 in userDetails.Id .

export interface UserDetails {
    Id: string;
}

export interface IProps {
    userDetails: UserDetails
}

export interface IState {
    combinedURL: string;
}

export default class EntryForm extends React.Component<IProps, IState> {

    constructor(props : IProps) {
        super(props);
        this.state = {
            combinedURL: 'MonkeyFace12' as string
        };
        this.createCombinedURL = this.createCombinedURL.bind(this);
    } 

    async createCombinedURL() {
        try {
            this.setState({ combinedURL: 'This is the Start of the URL followed by ' + this.props.userDetails.Id });
        } catch (e) {
            console.log("Error setting CombinedURL");
        }
    }

    async componentDidMount() {
        try {
            await this.createCombinedURL();
        } catch (error) {
        }
    }

    render() {
        return (
            <>
                <FormGroup row>
                    <Label
                        sm={1}>
                        Client
                    </Label>
                </FormGroup>

                <Button color="primary" type="submit">
                    Sign in
                </Button>
            </>
        );
    }
}

When I check the value of this.state.CombinedURL it is still MonkeyFace12.

The function CreateCombinedURL does not seem to affect it at all.

I was like you not long ago. I actually found that using arrow functions works a log smoother for a lot of the situations that I came across, and I came from Java where classes are key.

Using an arrow functions and hooks look a lot neater in my opinion as well. You don't have to worry about the 'this.' keyword at all. Hooks are amazing tools that also replace some of the lifecycle methods as well. Below is just an example of how much cleaner it can be.


import React, { FC, useState } from 'react'

interface IProps {
   username: string
}

const EntryForm: FC<IProps> = ({username}) => {
   const [combinedURL, setCombinedURL] = useState('Start of the URL here +')//sets up state for you without extra work
   
   useEffect(() => {
      //do something to the state
      setCombinedURL(combinedURL + username)
   }, [])//This dependency array determines when this method fires. Empty means it runs only once.

   return(
      <div>
         This is the combined URL {combinedURL}
         <input type='text' onChange={e => {
            setCombinedURL(e.target.value); //Or whatever else you want to happen.
         }}>
      </div>
   )

}

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