mysql - React/Redux - 将项目存储在状态中并将其发送到数据库

标签 mysql reactjs redux react-redux redux-thunk

我正在构建一个应用程序,该应用程序的一部分是它允许人们收藏某些项目。他们只需单击 SVG 心形图标,它就会变成红色,并以状态存储到“收藏夹”,并发送到数据库 (MySQL)。如果他们再次单击该图标,它会变回灰色,将其从状态中删除,并再次运行数据库提取以删除该项目。

我一直在尝试将其构建到我的 Action 创建器中,但我无法让它们都工作(也就是说,我无法将其发送到状态和数据库)。然而,我确实让它完美地适合国家作品。我把它放在下面:

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

提前致谢!

最佳答案

您应该用经典的 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
    });
}

关于mysql - React/Redux - 将项目存储在状态中并将其发送到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52037332/

相关文章:

reactjs - 如何将 popover MATERIAL-UI 功能组件转换为基于类的组件?

git - gh-pages d-构建 : failed at deploy script

reactjs - React 哈希路由和子路由

javascript - Redux 表单操作未定义

javascript - 尽管使用 props 而不是 state,但无法读取 React-redux 上未定义错误的属性 'map'

mysql - 为什么我的查询不使用日期时间字段上的索引?

mysql - 查询选择: who two employee works for the same company

添加和或子句时MySql Left Join速度慢

mysql - sql : Flag the next few rows of a column based on another column value

javascript - 成功重定向后 react 不呈现组件