如何从 useState 更改为 useReducer

how to change from useState to useReducer

以下代码我试图将其转换为 useReducer 但有些事情我无法弄清楚。在以下代码中,handleClick 更新状态并调用其他函数以执行进一步的操作。在useReducer中,我可以更新状态但是如何调用其他函数。

 const handleClick = (id) =>{
    let matchedEl = userArray.find(el => el.pic == picArray[id].pic)
    if(matchedEl){
        alert('game over')`
        setUserArray([]);
        gameOver();
    } else {
        let picObj = { "pic": picArray[id].pic}
        setUserArray([...userArray, picObj]) //updates the state
        if(userArray.length == 12){
            setUserArray([])
            scoreFn();
            return;
        }
        let shuffledArray = shufflePicArray();
        setPicArray([...shuffledArray]) //updates the state
        scoreFn();
    }   
}

return (
        <Container >
                        <Card onClick={() => handleClick(id)} /> </Card>
            </Row>             
        </Container>)}
  

使用Reducer

const initialState = {
    picArray: pics,
    userArray: []
}
function reducer(state, action){
    switch(action.type){
        case "handleClick" :
        {
            let id = action.payload;
            const shuffledArray = state.picArray.sort( () => Math.random() - 0.5)
            let matchedEl = state.userArray.find(el => el.pic == state.picArray[id].pic)
            console.log(matchedEl)
            let picObj;
            if(!matchedEl){
                    picObj = { "pic": state.picArray[id].pic}
                } else {
                    alert('game over')
                    gameOver(); //can't call the function is not defined yet
                }
        return{
            state,
           picArray:[...shuffledArray], //this works
           userArray:[...state.userArray, picObj] //this works
        }
    }
    default:
      return state;
    }
}

const Newmain = ({scoreFn, gameOver}) => {
    const [state, dispatch] = useReducer(reducer, initialState)

return(
<card onClick={() =>dispatch({type:'handleClick', payload:id})} />
)}```


The useState handleClick function does a lot more things and how to reproduce while using useReducer. 

要回答您的问题,您可以添加

const handleClick = (id) => {
//do stuff here
dispatch({type:'handleClick', payload:id})
}


然后是 <card onClick={() => handleClick(id)} />,但我建议根据您的用例使用 useCallback