首页 > 解决方案 > 类型“null”不可分配给类型“Dispatch” | 反应商店

问题描述

我正在构建一个应用程序来删除文件并刷新表,pushFile当我将文件放在特定区域时触发事件,我正在使用dispatch函数将文件推送到减速器,减速器查看case并推送将文件放入dataRows存储中的数组中,我还使用一些checkboxes来过滤数据,我也使用dispatch函数将这些过滤器推送到reducer,我的主要问题是如何初始化存储并在这部分给它一个默认值代码:到目前为止,我正在传递null,正如您在这一行中看到的那样: const store = createContext<ContextType | null>(null); 我试图传递initialState对象,但它没有让我这样做并给了我一个错误

'{ state: { searchFilter: string[]; 类型的参数 数据行:数据行[];}; 调度:空;}' 不可分配给“ContextType”类型的参数。属性“调度”的类型不兼容。类型 'null' 不能分配给类型 'Dispatch<{ type: string; 值:未知;}>'

我想要一种方法来创建一个dispatch我可以分配给调度的实例。 或者任何其他让我重构我的减速器的解决方案,所以它不需要dispatch在商店中有 a ,但是我将如何公开它以在DropZone?

const initialState = {
  state : {
    searchFilter: initFilter,
    dataRows: initDataRows
  },
  dispatch: null
};


interface ContextType {
    state: {
      searchFilter: string[];
      dataRows: DataRow[];
    };
    dispatch: React.Dispatch<{ type: string; value: unknown }>;
  };



const store = createContext<ContextType | null>(null);

const StateProvider = ( { children} : any ) => {
  const [state, dispatch] = useReducer((state : any, action:{type:string, value:any}) => {
    console.log("I'm inside reducer hey hey hey");
    console.log("state : ", state);
    switch(action.type) {
        case "dateChecked": 
            //console.log("dateChecked: ", action.value);
            if(state.searchFilter && state.searchFilter.includes(action.value)){
                const searchFilter = state.searchFilter.filter((v: string) => v !== action.value);
                const newState = { ...state, searchFilter };
                //state.searchFilter = newSearchFilter;
                return newState;
            }else{
                state.searchFilter.push(action.value);
            }  
        break;
        case "dataIssueChecked":
          console.log("dataIssueChecked: ", action.value);
            if(state.searchFilter.includes(action.value)){
                let searchFilter = state.searchFilter.filter((v: string) => v !== action.value);
                const newState = { ...state, searchFilter };
                return newState;
            }else{
                state.searchFilter.push(action.value);
            }
        break;
        case "UPDATE_TABLE":
            console.log("UPDATE_TABLE in store scope : ", action.value);
            console.log("state : ", state);
            console.log("state.dataRows : ", state.dataRows);
            state.dataRows =  action.value;
        break;
      default:
        throw new Error();
    };
  }, initialState);

  return <Provider value={{ state, dispatch }}>{children}</Provider>;
};

标签: javascriptreactjstypescriptreact-redux

解决方案


推荐阅读