inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

웹 게임을 만들며 배우는 React

TicTacToe에서 onClickTable에 역할을 알고싶습니다.

200

sbl133

작성한 질문수 2

0

import React, {useEffectuseReduceruseCallbackfrom 'react';
import Table from './Table';

const initialState = {
    winner: '',
    turn: 'O',
    tableData: [['','',''],['','',''],['','','']],
    recentCell: [-1, -1],
};

export const SET_WINNER = 'SET_WINNER';
export const CLICK_CELL = 'CLICK_CELL';
export const CHANGE_TURN = 'CHANGE_TURN';
export const RESET_GAME = 'RESET_GAME';

const reducer = (stateaction=>{
    switch(action.type){
        case SET_WINNER:
            return {
                ...state,
                winner: action.winner,
            };
        case CLICK_CELL:{
            const tableData2 = [...state.tableData];
            tableData2[action.row] = [...tableData2[action.row]];
            tableData2[action.row][action.cell] = state.turn;
            return{
                ...state,
                tableData: tableData2,
                recentCell: [action.rowaction.cell],
            }
        }
        case CHANGE_TURN:{
            return{
                ...state,
                turn: state.turn === 'O' ? 'X' : 'O',
            }
        }
        case RESET_GAME:{
            return{
                ...state,
                turn: 'O',
                tableData: [['','',''],['','',''],['','','']],
                recentCell: [-1, -1],
            }
        }
        default:
            return state;
    }
};

const TicTacToe=()=>{
    const [statedispatch] = useReducer(reducerinitialState);
    const {tableDataturnwinnerrecentCell} = state;

    const onClickTable = useCallback(()=>{
        console.log("onClickTable")
        dispatch({type: SET_WINNERwinner: 'O'});
    }, [])
    useEffect(()=>{
        const [rowcell] = recentCell;
        if(row < 0){
            return;
        }
        let win = false;
        if(tableData[row][0] === turn && tableData[row][1] === turn && tableData[row][2] === turn){
            win = true;
        }
        if(tableData[0][cell] === turn && tableData[1][cell] === turn && tableData[2][cell] === turn){
            win = true;
        }
        if(tableData[0][0] === turn && tableData[1][1] === turn && tableData[2][2] === turn){
            win = true;
        }
        if(tableData[0][2] === turn && tableData[1][1] === turn && tableData[2][0] === turn){
            win = true;
        }
        if(win){
            dispatch({type: SET_WINNERwinner: turn});
            dispatch({type: RESET_GAME});
        }
        else{
            let all = true;
            tableData.forEach((row)=>{
                row.forEach((cell)=>{
                    if(!cell){
                        all = false;
                    }
                })
            })
            if(all){
                dispatch({type: RESET_GAME});
            }else{
                dispatch({type: CHANGE_TURN});
            }
        }
    }, [recentCell])
    return(
        <>
        <Table onClick = {onClickTable} tableData={tableData} dispatch={dispatch}/>
        {winner && <div>{winner}님의 승리</div>}
        </>
    );
}

export default TicTacToe;
위에 코드에서 onClickTable이 어떤역할을 하는지 정확히 알고싶습니다.
함수 안에 console.log을 넣어봐도 실행중에 console창에 찍히지 않고,
Table component에 props로 전달되어도 해당 component에서 쓰이는거 같지도 않고,
Table에 자식component에 전달도 안되는것을 보니 어떤 역할을 하는것인지 아무리 생각해봐도 모르겠습니다.
긴 질문 읽어주셔서 감사합니다.

react

답변 1

0

제로초(조현영)

저거 아마 강좌에서 지웠던 것 같습니다. 지우지 않았더라도 필요없으니 빼셔도 됩니다.

npm run dev 실행 시 포트가 안뜨는 문제

0

202

2

timeouts.current를 useEffect 의 input값으로 넣었을때

0

85

2

렌더링 테스트 코드 (Hooks)

0

80

1

Cannot find package 'react-refesh' 이런 에러 뜨시는 분들 보세요.

0

149

1

해당 에러 뜨는 분들 보세요. "Uncaught TypeError: ReactDom.createRoot is not a function"

1

191

1

강사님 레포지토리에서 코드 복사 시 master 브랜치 말고 react18 브랜치꺼 복붙하세요ㅠㅠ

0

95

1

useMemo와 useCallback 사용 시기

0

205

2

onRightClickTd가 작동을 하지 않습니다.

0

226

1

action.type 불러오는 방식

0

222

2

onClickRedo 질문

0

172

1

const Try = require(./Try) 빨간줄

0

248

1

npx webpack 실행시

0

313

1

지뢰찾기 강좌에서 빈칸들 한번에 열기 파트에서 여쭤보고싶은부분이 있어서 글 올립니다.

0

234

1

강좌에서 다루지 않은 기능들은 어떻게 학습하면 좋을까요?

0

311

1

react devtool이 enable 않됩니다.

0

530

2

React 랜더링이 되지 않습니다.

0

409

2

비동기로 동작하는 setState에 대해서

0

331

1

npm run dev 할 때 에러발생

0

478

2

memo, PureComponenet, shouldComponentUpdate 관련 질문

0

206

1

devMiddleware의 필요성

0

352

1

리액트에서 화살표 함수를 사용해야하는 이유

0

932

2

path.join관련질문

0

280

2

2-9. 웹팩 데브 서버와 핫 리로딩 설치과정 시 에러

0

373

1

next.js 에서 이와 비슷한 예제를 돌리고있는데 react랑 달라서 질문 드립니

1

490

4