Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何使用useReducer在对象状态中设置多个值?_Reactjs_React Hooks - Fatal编程技术网

Reactjs 如何使用useReducer在对象状态中设置多个值?

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

我试图使用函数的结果在reducer中设置对象状态中的两个值。正在为
结果
获取未定义的值

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;
};