From e95d3b91654191cd0348e201c33290b586982ca3 Mon Sep 17 00:00:00 2001 From: haerong22 Date: Mon, 22 Mar 2021 20:40:21 +0900 Subject: [PATCH] react web game : Context API - createContext, Provider --- react_webgame/main/Form.jsx | 13 +++++++--- react_webgame/main/MineSearch.jsx | 41 ++++++++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/react_webgame/main/Form.jsx b/react_webgame/main/Form.jsx index a44fb57c..03657786 100644 --- a/react_webgame/main/Form.jsx +++ b/react_webgame/main/Form.jsx @@ -1,9 +1,11 @@ -import React, { useState, useCallback } from "react"; +import React, { useState, useCallback, useContext } from "react"; +import { START_GAME, TableContext } from "./MineSearch"; const Form = () => { const [row, setRow] = useState(10); const [cell, setCell] = useState(10); const [mine, setMine] = useState(20); + const { dispatch } = useContext(TableContext); const onChangeRow = useCallback((e) => { setRow(e.target.value); @@ -14,9 +16,12 @@ const Form = () => { const onChangeMine = useCallback((e) => { setMine(e.target.value); }, []); - const onClickBtn = useCallback((e) => { - setMine(e.target.value); - }, []); + const onClickBtn = useCallback( + (e) => { + dispatch({ type: START_GAME, row, cell, mine }); + }, + [row, cell, mine] + ); return (
diff --git a/react_webgame/main/MineSearch.jsx b/react_webgame/main/MineSearch.jsx index f73e4269..690f80b1 100644 --- a/react_webgame/main/MineSearch.jsx +++ b/react_webgame/main/MineSearch.jsx @@ -1,14 +1,43 @@ -import React, { useReducer } from "react"; +import React, { createContext, useReducer, useMemo } from "react"; +import Form from "./Form"; import Table from "./Table"; +// 칸의 상태에 따라 코드 부여 +export const CODE = { + MINE: -7, + NORMAL: -1, + QUESTION: -2, + FLAG: -3, + QUESTION_MINE: -4, + FLAG_MINE: -5, + CLICKED_MINE: -6, + OPENED: 0, // 0 이상이면 다 opened +}; + +// context api +export const TableContext = createContext({ + tableData: [], + dispatch: () => {}, +}); + +// state 초기값 const initialState = { tableData: [], timer: 0, result: "", }; +// action 명 +export const START_GAME = "START_GAME"; + +// action 동작 정의 const reducer = (state, action) => { switch (action.type) { + case START_GAME: + return { + ...state, + tableDate: plantMine(action.row, action.cell, action.mine), + }; default: return state; } @@ -16,14 +45,18 @@ const reducer = (state, action) => { const MineSearch = () => { const [state, dispatch] = useReducer(reducer, initialState); - const { result } = state; + + const value = useMemo(() => { + tableData: state.tableData, dispatch; + }, [state.tableData]); + return ( - <> +
{timer}
{result}
- + ); };