从父级向子级发送道具并在子组件(ReactJs)中更新它们

问题描述 投票:0回答:1

我尝试使用 ReactJs 发出的 API 请求的响应进行分页。我有一个 Main.js 页面,它将道具发送到子组件,即 PageButtons.js。一切都很顺利,我通过控制台记录我传递的值的 this.props 检查了这一点。
问题是我需要更新 props 的状态,并且我需要在 parent 组件(即 Main.js)上进行更新。我使用它来增加 fetch API 请求的限制值和偏移量,具体取决于我刚刚单击的按钮,但这不会发生...:(

这个问题有更多细节,比如获取响应的数组(仅使用 ReactJs 进行 API 获取的客户端分页)。

我将保留 Main.js 代码(不包括导入):

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>
        )
    }
}

}

现在 PageButtons.js 代码:

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>
        )
    }

}
javascript reactjs fetch-api react-props
1个回答
1
投票

将以下方法添加到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 渲染方法更改:

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

PageButtons.js 更改。

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);
};
© www.soinside.com 2019 - 2024. All rights reserved.