juriy / pro-react-redux Goto Github PK
View Code? Open in Web Editor NEWSource code for Pro React Redux online course
Source code for Pro React Redux online course
Здесь вы почему-то отказываетесь от декларативного подхода в пользу императивного:
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 в консоле появляется предупреждение:
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;
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.