javascript - ReactJS - 从 reducer 返回单个项目的操作

标签 javascript reactjs react-redux immer.js

这里的目标是从我的组件调用一个操作并从reducer获取单个对象,然后使用该对象,我将加载我的表单。

Redux 正在工作,但它返回我想要作为整个状态的单个对象

我的组件:

const dispatch = useDispatch()

const rewardFromRedux = dispatch(getProductForUpdateAction('reward', rewardIdForUpdate))

// After getting the information from redux, I will load my component state like this:
const [title, setTitle] = useState(rewardFromRedux ? rewardFromRedux.title : '')
const [about, setAbout] = useState(rewardFromRedux ? rewardFromRedux.about : '')

我的行动:

// receives a product type (survey, reward) and the productId
// and call action to get the product from the reducer

export function getProductForUpdate(productType, productId) {
  switch (productType) {
    case 'reward':
      return {
        type: actions.GET_REWARD_FOR_UPDATE,
        payload: productId,
      }

    default:
      return null
  }
}

我的 reducer :

case GET_REWARD_FOR_UPDATE:
   return produce(state, draft => {
     const rewardIndex = draft.campaign_products.reward.rewards.findIndex(
       p => p.uuid === action.payload,
     )
     if (rewardIndex >= 0) {

       // the problem is here, is returning the item that I want but as my whole state
       // state.campaign_products.reward.rewards is my array of reward objects

       return state.campaign_products.reward.rewards[rewardIndex]
     }
   })

如何才能只返回我想要的对象?

最佳答案

创建然后使用选择器

选择器

export const getRewardByIndex = (rewardIndex) => (state) => {
  return state.campaign_products.reward.rewards[rewardIndex];
};

在你的组件中

import { useSelector } from 'react-redux';

const someIndex = 0;
const reward = useSelector(getRewardByIndex(someIndex));

关于javascript - ReactJS - 从 reducer 返回单个项目的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59536716/

相关文章:

javascript - React Redux 首次加载时存储为空

javascript - React Bootstrap 模态

javascript - 无法在服务器端 NodeJS 上启用 CORS

javascript - 在(Phonegap 应用程序)中构建不填充 IOS 设备上的字段的方形表单构建

reactjs - 找不到模块 : Can't resolve '../axios' in 'F:\React\react-complete-guide\src\Component'

reactjs - 在项目上运行formatjs提取时,未返回任何消息。有什么想法吗?

javascript - AngularJS:自定义指令不适用于 dirPagination

javascript - 将多个 PDF 页面合并/嵌套为一个

javascript - Material UI 中的嵌套按钮 : how to disable ripple effect of container button while clicking on a child button?

javascript - 如何在 react 导航 5.x 中隐藏选项卡导航(底部选项卡)的标题?