我正在尝试使用函数的结果在化简器中的对象状态下设置两个值。获得result
的undefined值。
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' });
}
答案 0 :(得分:1)
请确保不仅使用state.charCountsFirstName
,而且要使用charCountsFirstName
。
...
switch (action.type) {
case 'SET_ALL_FREQS_FIRSTNAME':
let result = getAllFrequencies(state.charCountsFirstName); <---- like this.
return {
...state,
allFreqsFirst: {
labels: result[0],
data: result[1],
}
};
default:
return state;
}
...
答案 1 :(得分:0)
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;
};