简体   繁体   中英

Send props from parent to child and update them in child component (ReactJs)

I trying to make a pagination with a response from an API request made with ReactJs. I have one Main.js page that send props to child component which is PageButtons.js . Everything is passing well, I checked that by console logging this.props of the values I passed.
The thing is I need to update the state of props and I need that to get updated on parent component, which is Main.js. I'm using this to increment the value of limit and offset of the fetch API request, depending on the button I just clicked, but that does not happen... :(

This question as little bit more details, like the array of the fetch response ( Client-side pagination of API fetch only with ReactJs ).

I'll leave here Main.js code (no imports included):

export class Main extends React.Component {

    constructor(props) {
        super(props);
    this.state = {
        token: {},
        isLoaded: false,
        models: [],
        offset: offset,
        limit: limit
    };
}

componentDidMount() {

    /* here is other two fetches that ask for a token */

    fetch(url + '/couch-model/', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
        }
    }).then(res => {
        if (res.ok) {
           return res.json();
       } else {
            throw Error(res.statusText);
       }
    }).then(json => {
    this.setState({
            models: json.results
        }, () => {});
   })
}


render() {

    const { isLoaded, models } = this.state;

    if (!isLoaded) {
        return (
            <div id="LoadText">
                Estamos a preparar o seu sofá!
            </div>
        )
    } else {

        return (
            <div>

               {models.map(model =>
                    <a href={"/sofa?id=" + model.id} key={model.id}>
                        <div className="Parcelas">
                            <img src={model.image} className="ParcImage" alt="sofa" />
                            <h1>Sofá {model.name}</h1>

                            <p className="Features">{model.brand.name}</p>

                            <button className="Botao">
                                <p className="MostraDepois">Ver Detalhes</p>
                                <span>+</span>
                            </button>
                            <img src="../../img/points.svg" className="Decoration" alt="points" />
                        </div>
                    </a>
                )}

                 <PageButtons limit={limit} offset={offset}/>

            </div>
        )
    }
}

}

And now PageButtons.js code:

export class PageButtons extends React.Component {

    ButtonOne = () => {
        let limit = 9;
        let offset = 0;
        this.setState({
            limit: limit,
            offset: offset
        });
    };

    ButtonTwo = () => {
        this.setState({
            limit: this.props.limit + 9,
            offset: this.props.offset + 9
        });
    };

    render() {

        console.log('props: ', this.props.limit + ', ' + this.props.offset);

        return (
            <div id="PageButtons">
                <button onClick={this.ButtonOne}>1</button>
                <button onClick={this.ButtonTwo}>2</button>
                <button>3</button>
                <button>></button>
            </div>
        )
    }

}

Add below methods to Main.js

fetchRecords = (limit, offset) => {
    // fetch call code goes here and update your state of data here
}


handleFirstButton = (limit, offset) => {
    this.setState({limit : limit, offset: offset})
    this.fetchRecords(limit, offset)
}

handleSecondButton = (limit, offset) => {
    this.setState({limit: limit, offset : offset})
    this.fetchRecords(limit, offset)
}

Main.js render method changes :

<PageButtons 
    limit={limit} 
    offset={offset} 
    handleFirstButton={this.handleFirstButton} 
    handleSecondButton={this.handleSecondButton}/>

PageButtons.js changes.

ButtonOne = () => {
    let limit = 9;
    let offset = 0;
    this.props.handleFirstButton(limit, offset);
};

ButtonTwo = () => {
    let {limit, offset} = this.props;
    limit += 9;
    offset += 9;
    this.props.handleSecondButton(limit, offset);
};

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