server.get('/product/:slug');
server.get('/some_route', (req, res) => /* ... */);
server.get('/some_other_route', (req, res) => /* ... */);
server.get('/:product', (req, res) => /* ... */);
loadPage = () => {
Progress.show();
this._hideAllTimeout = setTimeout(() => Progress.hideAll(),800);
}
componentWillUnmount() {
clearTimeout(this._hideAllTimeout);
}
Не понятно почему эта херня будет выполняться параллельно
const await1 = await pause500ms(); // ожидаем 500мс разрешение промиса и получаем undefined
const await2 = await pause500ms(); // ожидаем 500мс разрешение промиса и получаем undefined
await await1; // передаем undefined и получаем разрешенный промис
await await2; // передаем undefined и получаем разрешенный промис
console.log("I will be logged after 500ms"); // No, you will be logged after 1000ms
await await1;
и await await2;
на первый взгляд не оказывают влияния на код, но это не так.(async() => {
await console.log(1);
await console.log(2);
console.log(3);
})();
console.log(4);
(async() => {
await console.log(5);
console.log(6);
})();
console.log(7);
// 1
// 4
// 5
// 7
// 2
// 6
// 3
Какой промис возвращает функция - разрешенный или нет?
function pause500ms() {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(); // вот тут разрешается созданный Promise
}, 500);
});
}
В константу await1 записывается функция(?) или результат ее исполнения, а именно промис?
А здесь, получается, функция вызывается?
await await1;
await await2;
console.log("I will be logged after 500ms");
Promise.resolve(undefined).then(() => {
Promise.resolve(undefined).then(() => {
console.log("I will be logged after 500ms");
});
});
Что значит возвращает промис?
// Что значит промис. Промис, это спецобъект, содержащий свое состояние и инструкции, которые необходимо исполнить после достижения того или иного состояния. Так? Так.
this.setState({
showCurrentUserInfo: conversation,
}, () => {
console.log(this.state.conversation);
});
componentDidUpdate(prevProps, prevState) {
console.log('prev conversation: ', prevState.conversation);
console.log('new conversation: ', this.state.conversation);
}
this.setState(state => ({
todoList: [...state.todoList, { id: nanoid(8), text: value, done: false }],
}));
{this.state.todoList.map(todo => (
<Todo click={this.handleClick} key={todo.id} todo={todo} />
))}
const array = ['first', 'second'];
let output;
function allOdd(words) {
let result = true;
for (let i = 0; i < words.length; ++i) {
const len = words[i].length;
if (len % 2 !== 0) {
result = false;
break;
}
}
return result;
}
output = allOdd(array);
alert(output);
function length(string) {
return prop('length', string);
}
function odd(number) {
return equals(modulus(number, 2), 0);
}
function allOdd(...words) {
return every(compose(odd, length), words);
}
alert(allOdd('first', 'second'));
const property = 'value';
foo({ property }); // эквивалентно foo({ property: property });
function foo(obj) {
console.log(obj.property);
}
function foo({ property }) {
console.log(property);
}
function foo(obj) {
const property = obj.property;
console.log(property);
}
function foo(obj) {
const { property } = obj;
console.log(property);
}
const mapDispatchToProps = {
fetchOnePhone,
};
componentDidMount() {
const { phonestoreService, match, fetchOnePhone } = this.props;
const { id } = match.params;
fetchOnePhone(phonestoreService, id);
}
fetchOnePhone(id);
handleSubmit = e => {
if (e.keyCode === 13) {
const { value } = e.target;
this.setState(prevState => ({
todoValue: [...prevState.todoValue, value],
}));
e.target.value = '';
}
};
handleSubmit = e => {
if (e.keyCode === 13) {
e.persist();
this.setState(
prevState => ({
todoValue: [...prevState.todoValue, e.target.value],
}),
() => {
e.target.value = "";
}
);
}
};
{this.state.todoValue.map((item, index) => (
<Li key={index} text={item} />
))}
В чём разница между созданием компонентов, через: стрелочную функцию, классами из новых версийES и React.createClass.
А так же, чем лучше пользоваться?
sum(1,2)
массив аргументов [1,2]
.if (!checks[i](arguments[i]))
вызывает функцию проверки из массива checks по индексу i, передает в нее аргумент из arguments по индексу i и возвращает результат в условие. for (var i = 0; i < arguments.length; i++) {
if (!checks[i](arguments[i])) {
alert("Некорректный тип аргумента номер " + i);
return;
}
}
sum(1,2)
, эквивалентен вызову:if (!checkNumber(1)) {
alert("Некорректный тип аргумента номер 0");
return;
}
if (!checkNumber(2)) {
alert("Некорректный тип аргумента номер 1");
return;
}
true
и ["array", "in", "sum?!?"]
не проходят проверку checkNumber. let cart = [];
// сумму тут хранить не надо
const initCart = () => {/* ... */};
const addProduct = (product, quantity) => {/* ... */};
const deleteProduct = id => {/* ... */};
const changeQuantity = (id, quantity) => {/* ... */};
const addProduct = (product, quantity) => {
const index = cart.indexOf(item => item.product.id = product.id);
if (index !== -1) {
cart = cart.map((item, i) =>
i === index ? { ...item, quantity: item.quantity + quantity } : item);
} else {
cart = [ ...cart, { product, quantity} ];
}
const sum = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
localStorage.setItem('cart', JSON.stringify(cart));
localStorage.setItem('sum', JSON.stringify(sum));
return dispatch => {
dispatch({
type: ADD_PRODUCT,
payload: {
cart,
sum,
},
});
};
}
if (index !== -1) {
cart[index].quantity += quantity;
} else {
cart.push({ product, quantity });
}
{
product,
quantity,
}
if (cup === "A") {
tempProducts = brasAll.filter(item => item.cup.includes("A"))
} else if (cup === "B") {
tempProducts = brasAll.filter(item => item.cup.includes("B"))
} else if (cup === "C") {
tempProducts = brasAll.filter(item => item.cup.includes("C"))
} else if (cup === "D") {
tempProducts = brasAll.filter(item => item.cup.includes("D"))
}
if (cup) {
tempProducts = tempProducts.filter(item => item.cup.includes(cup));
}
handleSearch = () => {
const { price, color, cup, shipping, search } = this.state;
this.props.dispatch(fetchProducts({ price, color, cup, shipping, search });
};
GET 'https://api.mysite.com/products?search=soes&price=120&color=red'