react/redux-存储状态为的项目并将其发送到数据库

wswtfjt7  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(365)

我正在构建一个应用程序,该应用程序的一部分是允许人们喜欢某些项目。他们只需单击svg的heart图标,它就会变成红色,并以状态存储到“favorites”中,然后发送到数据库(mysql)。如果他们再次单击图标,它会变回灰色,将其从状态中删除,并运行另一个数据库获取来删除该项。
我一直在尝试将它构建到我的action creator中,但是我不能让它们都工作(也就是说,我不能让它发送到state和数据库)。不过,我确实让它在国家片中发挥了完美的作用。我把它放在下面:

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
  })
}

提前谢谢!

ndh0cuux

ndh0cuux1#

应使用经典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
    });
}

相关问题