无法在componentDidMound函数中填写我的状态

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

在我的componentDidMount方法中,我试图通过使用访存来创建对象数组。在我的脑海中,它看起来像这样-在打开状态下,我保持变量“ loading”(默认情况下为true),并且在完成获取方法后,将其设置为false。在渲染方法上,我放置了if语句。但是在现实生活中,我的方法填充数组不会被执行(第一个console.log被执行,第二个没有被执行)。我对此一无所知。

import { Company } from "../company/company.component";

export class CompanyList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tempResult: 10,
            newArray: [],
            loading: true,
        };
    }

    componentDidMount = () => {
        console.log(this.state.loading,"1");
        const filledArray = this.props.companies.map((item) => {
            fetch(`xxxx/incomes/${item.id}`)
                .then((response) => response.json())
                .then((data) => {
                    let transactionsToFloat = data.incomes.map((item) =>
                        parseFloat(item.value)
                    );
                    let result = transactionsToFloat.reduce((acc, num) => {
                        return acc + num;
                    }, 0);
                    result = Math.round(result * 100) / 100;
                    this.setState({ tempResult: result, loading: false });
                    console.log(item.id, item.name, item.city, result);
                    return {
                        id: item.id,
                        name: item.name,
                        city: item.city,
                        totalIncome: result,
                    };
                });
            this.setState({ loading: false });
            return true;

        });
        this.setState({ newArray: filledArray });
    };

    render() {
        if (this.state.loading) {
            return <h1>Loading...</h1>;
        } else if (!this.state.loading) {
            return (
                <div>
                    {/* <button onClick={this.handleClick}>Button</button> */}
                    <table>
                        <thead>
                            <tr>
                                <th> Id </th>
                                <th> Name </th>
                                <th> City </th>
                                <th> Total income </th>
                            </tr>
                        </thead>

                        {this.state.newArray.map((item) => (
                            <Company key={item.id} company={item} />
                        ))}
                    </table>
                </div>
            );
        }
    }
}

欢呼声

reactjs
1个回答
0
投票

提取是异步的,当您在提取后执行this.setState({ loading: false })时,此行代码将立即执行,甚至无法兑现承诺。您也不返回数据,而是返回true值。

假设您正在执行一个promise数组,则可以考虑返回获取promise,并用Promise.all包装您的promise数组:

Promise.all(this.props.companies.map((item) => { return fetch().then().then() })
  .then(results => this.setState({ newArray: results, loading: false }))
  .catch(error => ... handle error here)

有一个警告,如果其中一项承诺失败,Promise.all将拒绝。如果您不希望这种行为,则可以改用Promise.allSettledallSettled永远不会拒绝,它会使用statusvalue键返回一个对象数组。

© www.soinside.com 2019 - 2024. All rights reserved.