如何使用接口传递数组对象或将它们存储在 reducer 中,过滤器如何处理它?

How to pass array objects or store them in reducer using interface and how does filter works on it?

我在使用 reducer 存储状态对象数组时遇到问题。我在下面有这段代码:

这是我的界面:

interface fontStyle {
     fontSize: number;
     fontData: FontFamily[];
}

interface FontFamily {
     family: string;
}

这是它加载的地方,reducers 只是存储状态。

const {state, dispatch} = fontReducer();
const font: fontData[] = []
for (let font in data.items) {
    font.push({ family: font.family,})
}
dispatch({type: 'fontStyle', action: font})

然后有一次我尝试用搜索做一个无序列表

<ul>
    {state.fontData.filter((item) => item.family.toLowerCase().includes(search)).map(font => (
         <li key={font.family}} onClick={selectFont}> {font.family} </li>
    ))}
</ul>

过滤器无法识别 fontData 并出现未定义的错误 => "TypeError: Cannot read property 'filter' of undefined"

这里是reducer -

const fontReducerHandler = () => { 
    switch (action.type) { 
        case "fontStyle": 
            return { ...state, fontData: action.fontData }
    }
}

const initialState: fontStyle { 
    fontSize: 0, 
    fontData: [], 
}

export const fontReducer = () => {
    const [state, dispatch] = useReducer(fontReducerHandler, initialState);
    return { state, dispatch }
}

问题

您似乎错误地访问了操作负载。你派遣

const font: fontData[] = [];
for (let font in data.items) {
  font.push({ family: font.family,});
}
dispatch({ type: 'fontStyle', action: font })

其中 action fontData 数组,但是在 reducer 中你访问 action.fontData 这是未定义。

const fontReducerHandler = () => { 
  switch (action.type) { 
    case "fontStyle": 
        return { ...state, fontData: action.fontData } // action.fontData undefined!!
  }
}

解决方案

正确访问操作负载。

const fontReducerHandler = () => { 
  switch (action.type) { 
    case "fontStyle": 
        return { ...state, fontData: action.action }
  }
}

或者您可以正确地构造动作对象以匹配它在 reducer 函数中的访问方式。

const font: fontData[] = [];
for (let font in data.items) {
  font.push({ family: font.family,});
}
dispatch({ type: 'fontStyle', fontData: font });

现在 action.fontData 已定义。