我正在构建一个应用程序,该应用程序的一部分是它允许人们喜欢某些项目。他们只需单击SVG心形图标,它就会变成红色,并以状态存储到“收藏夹”中,并以形式发送到数据库(MySQL)。如果他们再次单击该图标,它将恢复为灰色,将其从状态中删除,然后对数据库进行另一次提取以删除该项目。
我一直试图将其构建到动作创建器中,但是我无法同时使它们同时工作(也就是说,无法将其发送到状态AND到数据库)。但是,我确实使它对于状态块运行正常。我将其放在下面:
export const toggleFavorite = name => (dispatch, getState) => {
const { searchResults, favorites } = getState()
const currentSelection = filter(
selection => selection.name === name,
searchResults
)
const newFavorite = contains(currentSelection, favorites)
? reject(equals(currentSelection), favorites)
: append(currentSelection, favorites)
dispatch({
type: SET_FAVORITE,
payload: newFavorite
})
}
所以,我的问题是这样的:我在哪里以及如何将提取的内容放在后端以允许插入和删除?这是我最后一次失败的尝试:
export const toggleFavorite = name => async (dispatch, getState) => {
const { searchResults, favorites } = getState()
const currentSelection = filter(
selection => selection.name === name,
searchResults
)
const newFavorite = contains(currentSelection, favorites)
? reject(equals(currentSelection), favorites)
await fetch(`http://localhost:5000/deletefavorite?user_id=1&selection_id=${currentSelection}`)
: append(currentSelection, favorites)
await fetch(`http://localhost:5000/addfavorite?user_id=1&selection_id=${currentSelection}`)
dispatch({
type: SET_FAVORITE,
payload: newFavorite
})
}
谢谢!
答案 0 :(得分:0)
您应该用经典的if / else代替三元条件:
if (contains(currentSelection, favorites)) {
const newFavorite = reject(equals(currentSelection), favorites);
await fetch(`http://localhost:5000/deletefavorite?user_id=1&selection_id=${currentSelection}`);
dispatch({
type: SET_FAVORITE,
payload: newFavorite
});
} else {
const newFavorite = append(currentSelection, favorites)
await fetch(`http://localhost:5000/addfavorite?user_id=1&selection_id=${currentSelection}`);
dispatch({
type: SET_FAVORITE,
payload: newFavorite
});
}