简体   繁体   中英

ReactJS How to call a function to change JSON dict value after setState?

Let us say I currently have a ReactJS file where the code is like so:

class myFunction extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {}
        }
    }
    
    componentDidMount() {
        fetch('/api/data').then(r => r.json()).then(data => {
            this.setState({data: JSON_data})
    }

    render() {
        return(
                <h1>Name: {data.name}</h1>
                <p>Birthday:{data.birthday} </p>
        )
    }
}

export default myFunction;

Inside my data variable, it will be a library with two key/values (1 for name and 1 for birthday). So an example might be:

data = {
    "name": "Julia"
    "birthday": "9/3",
}

The website when I run will correctly show something like:

Name: Julia
Birthday: 9/3

However, I want to add a function that changes the birthday string from '9/3' to something like 'March 9th'. I have the function, we will call birthdayFormatter(), already implemented, but how would I call the function in a way where in setState, it would change the '9/3' to 'March 9th' so in the render return, I should see:

Name: Julia
Birthday: March 9th

I have been trying to call functions insider the render() return but none of these have worked. How would I do something like this? Just note that this should be done with no button clicks whatsoever, just normally loading the page.

You want to create a new object data with the new value for birthday after calling birthdayFormatter() , only then, store it in the state using setState() . Like so:

let currState = {...this.state};
currState.data.birthday = birthdayFormatter(currState.data.birthday);
this.setState(currState);

However, you said you want it done on loadup, so just call it after fetching and before setting the state:

class myFunction extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {}
        }
    }
    
    componentDidMount() {
        fetch('/api/data').then(r => r.json()).then(data => {
            data.birthday = birthdayFormatter(data.birthday); //here
            this.setState({data: JSON_data}); 
    }

    render() {
        return(
                <h1>Name: {this.state.data.name}</h1>
                <p>Birthday:{this.state.data.birthday} </p>
        )
    }
}

export default myFunction;

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