首页 > 解决方案 > React redux useSelector 和参数

问题描述

我试图理解为什么我似乎无法将参数传递给选择器。

本质上:我有一个存储数字和布尔值的逻辑 - 数字是我想要选择材料元素的参数 - 我有一个调度动作的按钮:

//on a jobcard - dispatches to the material logic slice, pushing the number into the redux state: materialforJobNumber;
 <button className="materialViewer"  onClick={() =>{dispatch(materialView(data.jobsessionkey))}}> MATERIAL</button>

它分派到逻辑切片:

//logic slice
materialView:(state, action)=>{
    console.log("what");
    console.log("material view succesfully called", action);
    const newState = {...state};
    console.log(newState);
    newState.materialforJobNumber = action.payload;
    newState.showMaterial=true;
    return newState
},
//the component that handles displaying the list of material for a job;

import {selectAttachedByJobKey} from "../MaterialCard/MaterialSlice";
const store= useStore();
const foundJN = store.getState().logic.materialforJobNumber;
const selectedJob=store.getState().jobs.find(x=>x.jobsessionkey==foundJN);
const materials = useSelector(selectAttachedByJobKey(foundJN));
const materialCards = materials.filter(x=>x.AttachedJobKey==foundJN).map((x,i)=><MaterialCard props={x} key ={i} />)


//material slice:
import { createSlice } from '@reduxjs/toolkit';

export const selectAttachedByJobKey = (state,action) =>{
    console.log("selecting material by job key",action);
    console.log(action?.payload);
    console.log(state);
    return state.material.filter(x=>x.AttachedJobkey===action?.payload);
}

我正在尝试通过单击按钮来显示“工作”的相关材料。我正在使用 createReducer 函数模式,我对如何实现这一点有点迷茫 - 有没有更简洁的方法来使用带有属性的选择器?

标签: javascriptreactjsreduxredux-reducers

解决方案


useSelector接受一个仅state作为参数的函数。如果你想传递其他变量,你可以使用柯里化方法:

export const selectAttachedByJobKey = (action) => (state) =>{
    console.log("selecting material by job key",action);
    console.log(action?.payload);
    console.log(state);
    return state.material.filter(x=>x.AttachedJobkey===action?.payload);
}

现在,当您这样做时,const materials = useSelector(selectAttachedByJobKey(foundJN));您将传递给useSelector一个可用的函数foundJN


推荐阅读