如果它们之间存在差异,则从 axios 响应更新状态的 属性

Update State's property from axios response, if difference between them

我想找到一种方法来比较来自 axios 的即将到来的响应与当前状态的 属性,并且仅当它们不同时,才使用带有响应的 setState 来替换那个 属性。否则跳过setState的使用,因为它们是相等的

componentWillReceiveProps(nextProps: Readonly<Props>, nextState: Readonly<State>): boolean {

        if (nextProps.isReloading !== this.state.isReloading) {
            // HERE we just confirm to proceed and change this prop
            this.setState({
                isReloading: nextProps.isReloading,
            });
            getData('/some-end-point')
                    .then((response: any) => { 
                      const newItems = response.data;

Already logged and confirmed they are equal, but the next line returns NO

                     this.state.items == newItems ? 'YES' : 'NO';

And after that only if different, update current state with the new one

                    })
                    .catch((error: any) => {
                        console.log(error);
                    });
            return true;
        }

        return false;
    }

我的假设是newItems是一个数组,

仅将它们与 ===== 进行比较是行不通的(各种原因无法解释)

如果 this.state.items 相同,不替换它有什么好处吗?

如果重要到你不调用 setState 如果它们相同,你可以通过循环数组并比较数组的每个元素来比较它们

newItems.length === this.state.items.length && newItems.sort().every((value, index)=> value === this.state.items.sort()[index]);

这是假设你的数组中的每个元素都是stringnumber,如果任何元素是另一个数组或者是一个对象,你必须在每个元素中进行类似的比较元素

我假设你可以使用 lodash isEqual 来做到这一点