개발정보

React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function

쿠카곰돌이 2023. 7. 5. 13:20
반응형

책보고 코딩 했는데 오류 발생.

React Hook "useState" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function
<Calc x={x} y={y} oper={oper} />

-----------------------------------------

type CalcPropsType = {
x: number;
y: number;
oper: string;
};

const Calc = (props: CountryListPropsType) => {
    let result: number = 0;
    switch(props.oper) {
        case "+":
            result = props.x + props.y;
        break;
        case "*":
            result = props.x * props.y;
        break;
        default:
            result = 0;
    };

    return (
        <div>
            <h3>연산방식 : {props.oper}</h3>
            <hr/>
            <div>
                {props.x} {props.oper} {props.y} = {result}
            </div>
        </div>
    );
};

 

어쨰든 왠지.. 하나로 넘겨 보내야 하지 않을 까? 해서

src\QuickStart\TopPage.tsx

import { useState } from "react";
import Calc from './Calc';
import {CountryListPropsType, CalcTypes} from './Calc';


const TopPage = () => {

    const [calcProps, setCalcProps] = useState<CalcTypes>(
       { x: 100, y: 200, oper:"+" }
    );

/*    
    const [x, setX] = useState<number>(100);
    const [y, setY] = useState<number>(200);
    const [oper, setOper] = useState<string>("+");
*/
/*
    const x= 100;
    const y= 200;
    const oper ="+";
*/
   
    return (
        <Calc caldata={calcProps}  />
    );
};

export default TopPage;

 

src\QuickStart\Calc.tsx

import React from 'react';

export type CountryListPropsType = {
    item: CalcTypes;
};

export type CalcTypes = {
    x: number;
    y: number;
    oper: string;
};

const Calc = (props: CountryListPropsType) => {
    let item = props.item;
    let result: number = 0;
    switch(item.oper) {
        case "+":
            result = item.x + item.y;
        break;
        case "*":
            result = item.x * item.y;
        break;
        default:
            result = 0;
    };

    return (
        <div>
            <h3>연산방식 : {item.oper}</h3>
            <hr/>
            <div>
                {item.x} {item.oper} {item.y} = {result}
            </div>
        </div>
    );
};

export default Calc;

 

연산방식 : +


100 + 200 = 300
반응형