Giter Site home page Giter Site logo

pro-react-redux's Issues

Non-declarative state update

Здесь вы почему-то отказываетесь от декларативного подхода в пользу императивного:

onDelete = (id) => {
    this.setState((state) => {
      const idx = state.items.findIndex((item) => item.id === id);
      const items = [
        ...state.items.slice(0, idx),
        ...state.items.slice(idx + 1)
      ];
      return { items };
    });
  };

Почему бы этот код не написать вот так, в одну строчку?

deleteItem = id => {
    this.setState(({ todoData }) => ({todoData: todoData.filter(el => el.id !== id)}));
  };

Функция filter возвращает новый массив, поэтому изначальный массив не изменяется.

То же самое и в этом коде:

toggleProperty = (arr, id, propName) => {
    const idx = arr.findIndex((item) => item.id === id);
    const oldItem = arr[idx];
    const value = !oldItem[propName];

    const item = { ...arr[idx], [propName]: value } ;
    return [
      ...arr.slice(0, idx),
      item,
      ...arr.slice(idx + 1)
    ];
  };

Вместо того, чтобы мучаться с нахождением индекса нужного элемента, а затем со сборкой/разборкой массива, лучше всё сделать при помощи одного прохода по массиву с использованием map:

toggleProperty = (arr, id, propName) => {
    // определяем вспомогательную функцию
    const inverseProp = (item, id, propName) => {
      item.id === id ? return { ...item, [propName]: !item[propName] : return item
    };

    // и при помощи map возвращаем новый массив
    return arr.map(el => inverseProp(el, el.id, propName));
  };

starDB, changeService Button

В приложение starDB при смене контекста по кнопке changeService в консоле появляется предупреждение:

index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in _temp (at with-child-function.js:6)
in Unknown (at with-data.js:65)

Для того, чтоб убрать данный warning в модуле hoc-helpers/with-data.js помогает добавить локальную переменную _isMounted для отслеживания состояния компонента, и состояние обновляется только если компонент ещё смонтирован.
Есть ли менее топорный вариант избежать данного предупреждения?
Может нужна более гибкая реализация swapi-service?

import React, { Component } from 'react';
import Spinner from '../spinner';
import ErrorIndicator from '../error-indicator';

const withData = (View) => {
  return class extends Component {
    **_isMounted = false;**

    state = {
      data: null,
      loading: true,
      error: false
    };

    componentDidUpdate(prevProps) {
      if (this.props.getData !== prevProps.getData) {
        this.update();
      }
    }

    componentDidMount() {
      **this._isMounted = true;**
      this.update();
    }

    componentWillUnmount() {
      this._isMounted = false;
    }

    update() {
      this.setState( {
        loading: true,
        error: false
      });

      this.props.getData()
        .then((data) => {
          **if (this._isMounted) {**
            this.setState({
              data,
              loading: false
            });
          }
        })
        .catch(() => {
          this.setState({
            error: true,
            loading: false
          });
        });
    }


    render() {
      const { data, loading, error } = this.state;

      if (loading) {
        return <Spinner />;
      }

      if (error) {
        return <ErrorIndicator />;
      }

      return <View {...this.props} data={data} />;
    }
  };
};

export default withData;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.