Reactjs 如何使用useReducer在对象状态中设置多个值?
我试图使用函数的结果在reducer中设置对象状态中的两个值。正在为Reactjs 如何使用useReducer在对象状态中设置多个值?,reactjs,react-hooks,Reactjs,React Hooks,我试图使用函数的结果在reducer中设置对象状态中的两个值。正在为结果获取未定义的值 const initialState = { charCountsFirstName: [7, 4, 2, 2, 2, 2, 2, 4, 5, 5, 5, 9], allFreqsFirst: { labels: [], data: [], }, } const getAllFrequencies = (arr) => { functio
结果
获取未定义的值
const initialState = {
charCountsFirstName: [7, 4, 2, 2, 2, 2, 2, 4, 5, 5, 5, 9],
allFreqsFirst: {
labels: [],
data: [],
},
}
const getAllFrequencies = (arr) => {
function getFreqs(arr) {
// DOO A BUNCH OF STUFF...
return [a, b];
}
const result = getFreqs(arr);
};
const reducer = (state, action) => {
switch (action.type) {
case 'SET_ALL_FREQS_FIRSTNAME':
let result = getAllFrequencies(charCountsFirstName);
return {
...state,
allFreqsFirst: {
labels: result[0],
data: result[1],
}
};
default:
return state;
}
}
const StateProvider = ({ children }) => {
const [newState, dispatch] = useReducer(reducer, initialState);
// CALL DISPATCH AFTER GETTING DATA FROM API CALL
dispatch({ type: 'SET_MOST_FREQUENT_FIRSTNAME' });
}
确保使用
state.charCountsFirstName
而不仅仅是charCountsFirstName
。。。
开关(动作类型){
案例“设置所有频率首名”:
让结果=getAllFrequencies(state.charCountsFirstName);
const getAllFrequencies = (arr) => {
function getFreqs(arr) {
// DOO A BUNCH OF STUFF...
return [a, b];
}
const result = getFreqs(arr);
// Maybe you need to return the val ==> 'result';
// Like: return result;
};