如何正确更新React Context状态并避免重新渲染?

时间:2019-10-27 11:51:21

标签: javascript reactjs ecmascript-6 react-context

我目前正在学习React Context API,并且我有一个包含以下文件的项目(我正在使用 create-create-app 生成项目):

├── package.json
├── node_modules
│   └── ...
├── public
│   └── ...
├── src
│   ├── components
│   │   ├── App.js
│   │   ├── Container.js
│   │   ├── Info.js
│   │   ├── PageHeading.js
│   │   ├── common
│   │   │   ├── Footer.js
│   │   │   ├── Header.js
│   │   │   ├── Helpers.js
│   │   │   ├── Loading.css
│   │   │   ├── Loading.js
│   │   │   └── SearchForm.js
│   │   └── list
│   │       ├── Pagination.js
│   │       └── Table.js
│   ├── css
│   │   └── ...
│   ├── fonts
│   │   └── ...
│   ├── images
│   │   └── ...
│   ├── index.css
│   ├── index.js
│   └── providers
│       └── GlobalProvider.js
└── yarn.lock

文件:src / index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import Header from "./components/common/Header";
import Footer from "./components/common/Footer";

ReactDOM.render(
    [<Header key='1' />, <App key='2' />, <Footer key='3' />],
    document.getElementById("root")
);

文件:src / providers / GlobalProvider.js

import React, { Component } from "react";
import { handleResponse } from "../components/common/Helpers";

// Set up initial context
export const GlobalContext = React.createContext({});

// Create an exportable consumer that can be injected into components
export const GlobalConsumer = GlobalContext.Consumer;

// Create the provider using a traditional React.Component class
class GlobalProvider extends Component {
    state = {
        age: 100,
        error: null,
        isLoading: false,
        currentPage: 1,
        result: "",
        data: null,
        total_hg_customers: "",
        total_grams_by_customers: "",
        totalPages: "",
        hasNextPage: false,
        hasPrevPage: false
    };

    fetchCustomersByPage = () => {
        this.setState({ isLoading: true });
        const { currentPage } = this.state;

        fetch(
            `https://api-server.com/customer_gold?pageNum=${currentPage}`
        )
            .then(handleResponse)
            .then(response => {
                const {
                    currentPage,
                    result,
                    data,
                    total_hg_customers,
                    total_grams_by_customers,
                    totalPages,
                    hasNextPage,
                    hasPrevPage
                } = response;

                this.setState({
                    isLoading: false,
                    currentPage,
                    result,
                    data,
                    total_hg_customers,
                    total_grams_by_customers,
                    totalPages,
                    hasNextPage,
                    hasPrevPage
                });
                console.log("API request done and state has been updated"); // <-- this one get infinitely generated
            })
            .catch(error => {
                this.setState({
                    error: error.errorMessage,
                    loading: false
                });
            });
    };

    render() {
        return (
            // value prop is where we define what values
            // that are accessible to consumer components
            <GlobalContext.Provider
                value={{
                    state: this.state,
                    fetchCustomersByPage: this.fetchCustomersByPage
                }}>
                {this.props.children}
            </GlobalContext.Provider>
        );
    }
}

export default GlobalProvider;

文件:src / components / common / Helpers.js

export const handleResponse = response => {
        return response.json().then(json => {
            return response.ok ? json : Promise.reject(json);
        });
    };

文件:src / components / App.js

import React, { Component } from "react";
import GlobalProvider from "../providers/GlobalProvider";
import PageHeading from "./PageHeading";
import Container from "./Container";

class App extends Component {
    render() {
        return (
            <GlobalProvider>
                <div className='root-container content'>
                    <PageHeading />
                    <Container />
                </div>
            </GlobalProvider>
        );
    }
}

export default App;

文件:src / components / Container.js

import React, { Component } from "react";
import Loading from "./common/Loading";
import Info from "./Info";
import SearchForm from "./common/SearchForm";
import Table from "./list/Table";
import Pagination from "./list/Pagination";
import { GlobalConsumer } from "../providers/GlobalProvider";

class Container extends Component {
    render() {
        return (
            <GlobalConsumer>
                {context => {
                    const { isLoading } = context.state;

                    if (isLoading) {
                        return (
                            <div className='loading-container'>
                                <Loading />
                            </div>
                        );
                    }

                    return (
                        <div className='middle-container'>
                            <div className='container'>
                                <div className='success-container'>
                                    <div className='row'>
                                        <Info />
                                        <SearchForm />
                                    </div>
                                    <div className='row'>
                                        <Table />
                                    </div>
                                    <div className='row pagination'>
                                        <Pagination />
                                    </div>
                                </div>
                            </div>
                        </div>
                    );
                }}
            </GlobalConsumer>
        );
    }
}

export default Container;

文件:src / components / list / Table.js

import React, { Component } from "react";
import { GlobalConsumer, GlobalContext } from "../../providers/GlobalProvider";

class Table extends Component {
    static contextType = GlobalContext;

    componentDidMount() {
        console.log("Hello");
        return this.context.fetchCustomersByPage();
    }

    render() {
        return (
            <div className='col-12'>
                <GlobalConsumer>
                    {context => {
                        const { data } = context.state;
                        return (
                            <table className='customer-list'>
                                <thead>
                                    <tr>
                                        <th width='50%'>Account Number</th>
                                        <th width='50%'>Gold Balance (g)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {data &&
                                        data.map(customer => (
                                            <tr key={customer.account_number}>
                                                <td>{customer.account_number}</td>
                                                <td>{customer.gold_balance}</td>
                                            </tr>
                                        ))}
                                </tbody>
                            </table>
                        );
                    }}
                </GlobalConsumer>
            </div>
        );
    }
}

export default Table;

现在的问题是它继续对API服务器进行API调用(一次又一次的无限调用)。当我删除this.setState({isLoading: false, currentPage, ...})部分时,它停止了对API服务器的无限调用。但是,当然,应用程序的isLoading状态停留在true,并且加载微调组件仍保留在视图中。

我所需要的只是向API服务器提交一个调用→分配对提供者/全局状态的响应→删除加载微调器→使用API​​调用中的数据呈现表视图。我尝试使用why-did-you-update程序包找出问题所在,但没有发现任何线索。

我在这里做错了什么?请向我指出。如果我错过了在此处粘贴任何重要文件的信息,请告诉我。谢谢。

1 个答案:

答案 0 :(得分:0)

是否可以使用React Hook?根据您的代码,我建议您将其分解为React Hook。如果是这样,您可以使用useCallback或useMemo挂钩。