以下代码我试图将其转换为 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>)}
使用减速器
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.