这里的目标是从我的组件调用一个操作并从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/