react web game : Context API - createContext, Provider

This commit is contained in:
haerong22
2021-03-22 20:40:21 +09:00
parent b5342a2645
commit e95d3b9165
2 changed files with 46 additions and 8 deletions

View File

@@ -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 (
<div>

View File

@@ -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 (
<>
<TableContext.Provider value={value}>
<Form />
<div>{timer}</div>
<Table />
<div>{result}</div>
</>
</TableContext.Provider>
);
};