⚛️ 기본 환경: IDE: VS code, Language: React

 

 

발생 Error

React에서 다음 Source Code를 실행할 경우,

1
2
3
4
5
6
7
8
9
10
  useEffect(() => {
    useState();
 
    console.log('EFFECT RUNNING');
 
    return () => {
      console.log('EFFECT CLEANUP');
    };
  }, []);
 
 
 

🚨 다음과 같은 오류 발생

React Hook "useState" cannot be called inside a callback.

React Hooks must be called in a React function component or a custom React Hook function

 

 

발생 원인

use로 시작하는 ReactHook을 ReactHook함수 안에서의 중첩 사용 또는 최상위가 아닌 수준에서 ReactHook 호출

 

 

해결 방법

ReactHook을 최상위 수준( =Component안에서 직접적 선언)에서 React 함수(returnType JSX) 또는 사용자 정의 함수 안에서만 직접적으로 호출

 

⚛️ 기본 환경: IDE: VS code, Language: React

 

 

발생 Error

React에서 다음 Source Code를 실행할 경우,

1
2
3
4
5
6
7
8
9
10
11
12
13
const emailReducer = (state, action) => {
  useState();
 
  if(action.type === 'USER_INPUT'){
    return {value : action.value, isValid: action.value.includes('@')};
  }
  if(action.type === 'INPUT_BLUR'){
    return {value : state.value, isValid: state.value.includes('@')};
  }
 
  return {value: '', isValid: false};
};
 
 
 

🚨 다음과 같은 오류 발생

React Hook "useState" is called in function "emailReducer" that is neither a React function component nor a custom React Hook function.

React component names must start with an uppercase letter. React Hook names must start with the word "use"

 

 

발생 원인

use로 시작하는 ReactHook을 React 함수(returnType JSX) 또는 사용자 정의 함수 밖에서 호출

 

 

해결 방법

ReactHook을 React 함수(returnType JSX) 또는 사용자 정의 함수 안에서 호출

 

⚛️ 기본 환경: IDE: VS code, Language: React

 

 

발생 Error

React에서 다음 Source Code를 실행할 경우,

1
2
3
4
5
6
7
8
9
10
  return (
    <AuthContext.Provider>
      <MainHeader isAuthenticated={isLoggedIn} onLogout={logoutHandler} />
      <main>
        {!isLoggedIn && <Login onLogin={loginHandler} />}
        {isLoggedIn && <Home onLogout={logoutHandler} />}
      </main>
    </AuthContext.Provider>
  );
 
 
 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const Navigation = (props) => {
  return (
    <AuthContext.Consumer>
      {(ctx) => {
        return (
          <nav className={classes.nav}>
            <ul>
              {ctx.isLoggedIn && (
                <li>
                  <a href="/">Users</a>
                </li>
              )}
            </ul>
          </nav>
        );
      }}
    </AuthContext.Consumer>
  );
};
 
 
 

🚨 다음과 같은 오류 발생

TypeError: Cannot read properties of undefined (reading 'isLoggedIn')

 

 

발생 원인

React.createContect()에서 기본값 설정 시, Provider 객체를 사용

 

 

해결 방법

1. Provider를 사용하지 않고 기본값 설정

1
2
3
4
5
6
7
8
9
10
  return (
    <Fragment>
      <MainHeader isAuthenticated={isLoggedIn} onLogout={logoutHandler} />
      <main>
        {!isLoggedIn && <Login onLogin={loginHandler} />}
        {isLoggedIn && <Home onLogout={logoutHandler} />}
      </main>
    </Fragment>
  );
 
 
 

 

2. value prop을 통한 객체 전달

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  return (
    <AuthContext.Provider
      value={{
        isLoggedIn: false,
      }}
    >
      <MainHeader isAuthenticated={isLoggedIn} onLogout={logoutHandler} />
      <main>
        {!isLoggedIn && <Login onLogin={loginHandler} />}
        {isLoggedIn && <Home onLogout={logoutHandler} />}
      </main>
    </AuthContext.Provider>
  );
 
 
 

 

⭐ 기본값이 있을 경우, Provider는 필요없으나 context에 선언된 객체값이 변하며 해당 값을 다른 Component와 공유하고자 할 경우 Provider 선언이 필요

▶ 기본값이 있으나 값의 변화가 있을 예정이어 Provider를 사용해야할 때는 value prop을 사용하여 기본값을 직접 전달

 

⚛️ 기본 환경: IDE: VS code, Language: React

 

 

발생 Error

React에서 다음 Source Code를 실행할 경우,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const App = () => {
  const [courseGoals, setCourseGoals] = useState([
    { text: "Do all exercises!", id: "g1" },
    { text: "Finish the course!", id: "g2" },
  ]);
 
  const addGoalHandler = (enteredText) => {
    setCourseGoals((prevGoals) => {
      const updatedGoals = [...prevGoals];
      updatedGoals.unshift({ text: enteredText, id: "goal1" });
      return updatedGoals;
    });
  };
 
  return (
    <div>
      <section id="goal-form">
        <CourseInput onAddGoal={addGoalHandler} />
      </section>
      <section id="goals">{content}</section>
    </div>
  );
};
 
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const CourseInput = (props) => {
  const [enteredValue, setEnteredValue] = useState('');
  const [isValid, setIsValid] = useState(true);
 
  const formSubmitHandler = (event=> {
    event.preventDefault();
    if (enteredValue.trim().length === 0) {
      setIsValid(false);
      return;
    }
    props.onAddGoal(enteredValue);
  };
 
  return (
    <form onSubmit={formSubmitHandler}>
      <div
        className={`${styles['form-control']} ${!isValid && styles.invalid}`}
      >
        <label>Course Goal</label>
        <input type="text" onChange={goalInputChangeHandler} />
      </div>
      <Button type="submit">Add Goal</Button>
    </form>
  );
};
 
 
cs

🚨 Add Goal 실행 시, 다음과 같은 경고 발생

Warning: Encountered two children with the same key, `goal1`.
Keys should be unique so that components maintain their identity across updates.
Non-unique keys may cause children to be duplicated and/or omitted

 

 

발생 원인

map()을 통해서 반복문을 실행 할 경우, key값을 중복하여 부여함

1
2
3
4
5
6
7
8
  const addGoalHandler = (enteredText) => {
    setCourseGoals((prevGoals) => {
      const updatedGoals = [...prevGoals];
      updatedGoals.unshift({ text: enteredText, id: "goal1" });
      return updatedGoals;
    });
  };
 
 
cs

addGoalHandler로 추가되는 데이터값의 id가 goal1으로 고정되어있으며,

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const CourseGoalList = props => {
  return (
    <ul className="goal-list">
      {props.items.map(goal => (
        <CourseGoalItem
          key={goal.id}
          id={goal.id}
          onDelete={props.onDeleteItem}
        >
          {goal.text}
        </CourseGoalItem>
      ))}
    </ul>
  );
};
 
 
cs

해당 id값을 이용하여 key값을 부여하였으므로 중복값 발생

 

 

해결 방법

중복되지 않은 key값 부여

1
2
3
4
5
6
7
8
  const addGoalHandler = (enteredText) => {
    setCourseGoals((prevGoals) => {
      const updatedGoals = [...prevGoals];
      updatedGoals.unshift({ text: enteredText, id: Math.random().toString() });
      return updatedGoals;
    });
  };
 
 
cs

 

⚛️ 기본 환경: IDE: VS code, Language: React

 

 

발생 Error

React를 실행하고자, 터미널에서 다음 명령어를 입력할 경우,

🚨 다음과 같은 Error 발생

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Local\npm-cache\_logs\2023-05-24T01_17_19_007Z-debug-0.log 

 

 

발생 원인

React 파일이 존재하지 않은 경로에서 npm 설치 시도

 

 

해결 방법

React 파일이 존재하지 폴더로 이동 후 npm 설치

 

+ 올바른 경로에서 npm install 시, 동일한 error가 발생 했을 경우,

 

 

 

참고 자료

 

[Npm Error] A complete log of this run can be found in:

안녕하세요. 디자인도 하고, 개발도 하는 '디발자 뚝딱'입니다. vscode 터미널에 npm install 혹은 npm i를 입력했을 때 npm ERR! A complete log of this run can be found in: 라는 에러 문구가 뜰 때가 있습니다. 매

anerim.tistory.com