Привет! Я создаю корзину для покупок и столкнулся с проблемами в IE. (Обратите внимание, что в других браузерах все работает как положено).
Итак, моя проблема для бывших:
У меня 5 товаров в корзине. Я нажимаю удалить товар на 1 предмете.
Я обновляю страницу, и этот пункт все еще там.
Когда я проверяю свою базу данных на предмет, он больше не существует, поэтому он был удален. Так почему же я все еще вижу этот элемент, который был удален на странице?
Это происходит только в IE.
мой компонент выглядит так
class Cart extends Component {
componentDidMount() {
console.log('executed') //I get executed in the console so that works.
this.props.fetchCart();
}
removeItem(productId) {
this.props.dispatch(removeItem(productId));
}
render() {
return (
<ul className='list-item'>
{
cart.items.map((item, index) => {
return (
<li className='list-group-item d-flex justify-content-between align-items-center' key={index}>
<img style={{ width: '150px', height: '100px' }} src={item.main_img} />
<h5>{item.title}</h5>
<small>quantity {item.quantity}</small>
<small>Price ${item.price}</small>
<button
onClick={() => this.removeItem(item.product_id)}>Remove</button>
</li>
)
})
}
</ul>
)
}
}
const mapStateToProps = (state) => {
console.log(state.cart) //Always get 5 items instead of 4 which I should get 4 cause I deleted 1
return {
cart: state.cart
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ dispatch, rmAlert }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Cart);
моя сага за fetchCart:
import { call, put, takeLatest } from 'redux-saga/effects';
import { FETCH_CART } from '../../constants/cart';
import { fetchedCartSuccessful, fetchedCartError} from
'../../actions/cart';
import axios from 'axios';
function* fetchCart() {
try {
const response = yield call([axios, axios.get], '/api/cart');
yield put(fetchedCartSuccessful(response.data));
} catch (e) {
yield put(fetchedCartError(e.response.data));
}
}
export function* watchFetchCart() {
yield takeLatest(FETCH_CART, fetchCart);
}
и моя сага для removeItem
import { call, put, takeLatest } from 'redux-saga/effects';
import { showAlert, rmAlert } from '../../actions/alert';
import { REMOVE_ITEM_IN_CART } from '../../constants/cart';
import { fetchCart } from '../../actions/cart';
import axios from 'axios';
function* removeItemInCart(action) {
yield put(rmAlert());
let alert = {};
try {
const response = yield call([axios, axios.post], '/cart/remove-item', {
productId: action.productId
});
alert.alertClass = 'alert-success';
alert.msg = response.data.success.msg;
yield put(fetchCart());
yield put(showAlert(alert));
} catch (e) {
alert.alertClass = 'alert-info';
alert.msg = e.response.data.error.msg;
yield put(showAlert(alert));
}
}
export function* watchRemoveItemInCart() {
yield takeLatest(REMOVE_ITEM_IN_CART, removeItemInCart)
}
На моем бэкэнде, где я беру корзину из базы данных mysql и отправляю обратно в ответ. Я console.log ('executing'), чтобы убедиться, что он выполняется, и нет console.log не отображается в консоли? Я понятия не имею, что происходит. Опять же, это работает, как и ожидалось, в Chrome и Firefox.
app.get('/api/cart', (req, res) => {
const userId = req.signedCookies['user_cookie'];
console.log('executing'); //no console log saying this executed ?
const sql = `SELECT *, cart.quantity * products.price as price
FROM cart
LEFT JOIN products ON products.product_id = cart.product_id
WHERE user_id='${userId}'`;
connection.query(sql, (err, result, fields) => {
if (err) {
return res.status(500).json({
error: {
msg: 'Something went wrong, couldn\'t GET cart'
}
});
}
let cart = { quantity: 0, total: 0, items: [] };
result.map(item => {
cart.quantity += item.quantity;
cart.total += item.price;
cart.items.push(item);
});
console.log(cart);
res.setHeader('content-type', 'text/javascript');
res.send(cart);
});
});
как проверить, сколько товаров должно быть в моей корзине? Я делаю это ниже, посещая этот маршрут
app.get('/all-carts', (req, res) => {
console.log(req.signedCookies['user_cookie'])
const sql = `SELECT * FROM cart`;
connection.query(sql, (err, results, feilds) => {
console.log(results);
res.setHeader('content-type', 'text/javascript');
res.send(results);
});
});
Я посещаю этот маршрут и получаю ответ с массивом из 4 элементов, как и ожидалось, потому что я удалил 1. Если я удаляю все элементы, я вижу пустой массив. Тем не менее, когда я просматриваю страницу корзины, я вижу еще 5 товаров?
ОБНОВЛЕНИЕ - когда я очищаю историю браузера, он показывает правильное количество товаров в корзине, почему я должен очищать историю браузера, чтобы увидеть какие-либо обновления в IE?