以下代码我正尝试将其转换为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.
答案 0 :(得分:1)
要回答您的问题,您可以添加
const handleClick = (id) => {
//do stuff here
dispatch({type:'handleClick', payload:id})
}
,然后按原样使用<card onClick={() => handleClick(id)} />
,但我建议根据您的使用情况使用useCallback