0

次のコードを 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>)}
  

useReducer を使用

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. 
4

1 に答える 1