"React가 Hooks 순서 변경을 감지했습니다." 그러나 Hooks가 순서대로 호출되는 것 같습니다.
사용하려고 합니다.Context
그리고.Reducers
훅 순서가 일정하지 않은 문제에 부딪힙니다.내가 알기로는, 그 명령만 있으면useHook(…)
그대로, 어떤 종류의 제어 흐름에서도 반환된 상태/업데이트 함수/컴포넌트를 호출해도 문제가 없습니다.그렇지 않으면 Function Components 맨 처음에 후크를 호출합니다.
내가 지금 만들고 있는 건Days
루프로요?아니면 다른 걸 놓쳤나요?
Warning: React has detected a change in the order of Hooks
called by Container. This will lead to bugs and errors if not fixed. For
more information, read the Rules of Hooks:
https://reactjs.org/docs/hooks-rules.html
Previous render Next render
------------------------------------------------------
1. useContext useContext
2. undefined useRef
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
의 풀버전Container
아래에 있습니다.에서 발췌한 것Day
아래, 참조처react-dnd
의useDrop
.
export const Container: FunctionComponent<Props> = () => {
let events = useContext(State.StateContext)
//let events: Array<Event.Event> = [] <- with this, no warning
const getDaysEvents = (day: Event.Time, events: Array<Event.Event>) => {
return events.map(e => {
const isTodays = e.startTime.hasSame(day, "day")
return isTodays && Event.Event({ dayHeight, event: e })
})
}
let days = []
for (let i = 0; i < 7; i++) {
const day = DateTime.today().plus({ days: i })
days.push(
<Day key={day.toISO()} height={dayHeight} date={day}>
{getDaysEvents(day, events)}
</Day>
)
}
return <div className="Container">{days}</div>
}
에서 발췌한 것Day
(Event
마찬가지로 를 사용합니다.useDrag
훅, 여기서와 같이 최상위 레벨에서도 불린다.)
const Day: FunctionComponent<DayProps> = ({ date, height, children }) => {
const dispatch = useContext(State.DispatchContext)
const [{ isOver, offset }, dropRef] = useDrop({
// …uses the dispatch function within…
// …
})
// …
}
단락 로직 사용으로 인해 쓰던 컴포넌트에서 동일한 오류 메시지가 발생했습니다.
이로 인해 다음 오류가 발생했습니다.
const x = useSelector(state => state.foo);
if (!x) { return ; }
const y = useSelector(state => state.bar);
그 이유는x
후크 리스트의 길이는 2이지만,x
리스트의 길이는 1 입니다.
오류를 해결하기 위해 조기 종료 전에 모든 후크를 사용해야 했습니다.
const x = useSelector(state => state.foo);
const y = useSelector(state => state.bar);
if (!x) { return ; }
답장으로 내 의견을 쓰는 중:
문제는 네가 전화하고 있다는 거야Event.Event()
반응 성분인 경우에도 직접 사용할 수 있습니다.이로 인해 리액션은 함수 내부의 훅 콜을Container
이벤트에 참여하도록 의도하셨음에도 불구하고요.
해결책은 JSX를 사용하는 것입니다.
return isTodays && <Event.Event dayHeight={dayHeight} event={e} />
JSX를 결과 JS 코드로 대체하면 이 기능이 작동하는 이유가 명확해집니다.
return isTodays && React.createElement(Event.Event, { dayHeight, event: e })
https://reactjs.org/docs/react-api.html#createelement 를 참조해 주세요.함수 컴포넌트를 직접 호출할 필요가 없습니다.리액션이 작동하는 방법은 항상 반응하도록 컴포넌트를 건네주고 적절한 시간에 함수를 호출하도록 하는 것입니다.
이 질문 대신 다른 이유로, 당신이 이것을 받았을 때error
실제로는 훅 구현에 대한 잘못된 관행 때문에 발생합니다.
1 - 최상위 수준의 콜훅만
루프, 조건 또는 중첩된 함수에 Hooks를 호출하지 마십시오.대신 항상 리액트 기능의 최상위 레벨에서 Hooks를 사용하십시오.
주의: 구현:
useState
기능 맨 위에 있는 후크
2 - 리액트 함수로부터의 콜훅만
일반 JavaScript 함수에서 Hooks를 호출하지 않음
3 - 테스트 중 오류 발생
컴포넌트를 테스트할 때 이 에러가 표시되는 경우는, 커스텀 훅을 설정하는 장소에 주의해 주세요(기능의 선두로 치환).
베스트 프랙티스
eslint를 사용하여 코드를 린트하여 리액트 훅 규칙 오류를 방지합니다.
npm 또는 실로 패키지를 설치하다
npm install eslint-plugin-react-hooks --save-dev
useEffect에서 여러 API 호출 호출
내 경우 여러 API 호출을 수행하고 각각의 API 호출을 다른 상태로 저장했기 때문에 이 오류가 발생하였습니다.하지만 그것을 하나의 상태로 바꾼 후에 나는 그것을 극복할 수 있었다.
const [resp, setGitData] = useState({ data: null, repos: null });
useEffect(() => {
const fetchData = async () => {
const respGlobal = await axios(
`https://api.github.com/users/${username}`
);
const respRepos = await axios(
`https://api.github.com/users/${username}/repos`
);
setGitData({ data: respGlobal.data, repos: respGlobal.data });
};
fetchData();
}, []);
질문 시나리오가 아니라 오류 그 자체입니다. 누군가에게 도움이 되었으면 합니다.
const { chatSession, userBelongsToSession } = useChatSession(session_id)
const { activeSession, setActiveSession } = useActiveChatSession()
const isCurrentActiveSession = useMemo(() => activeSession != null && activeSession.session_id === session_id, [activeSession, session_id])
if (chatSession == null || activeSession == null) {
return (<div></div>)
}
const Container = styled(BorderedContainer)`height: 72px; cursor: pointer;`
이 코드 조각에서 동일한 오류가 발생하며 useRef가 스타일링된 컴포넌트에 의해 호출되고 조건부 렌더링으로 인해 호출되지 않은 것과 관련이 있습니다.
if (chatSession == null || activeSession == null) {
return (<div></div>)
}
기본적으로는 훅은 null을 반환하고 내 컴포넌트는 useRef를 사용하지 않고 렌더링합니다.단, 실제로 훅이 채워지면 스타일링된 컴포넌트가 useRef를 사용하여 컴포넌트를 생성합니다.
if (chatSession == null || activeSession == null) {
return (<div></div>)
}
const Container = styled(BorderedContainer)`height: 72px; cursor: pointer;
작성 중인 테스트에서 다른 후크 메서드를 호출할 때 이 오류가 무작위로 발생하였습니다.내게 해결방법은 '스파이'에 있었다.useRef
하다
const useRefSpy = jest
.spyOn(React, 'useRef')
.mockReturnValueOnce({ whatever })
의 변경mockReturnValueOnce
로로 합니다.mockReturnValue
오류를 수정했습니다.
리액트 네이티브 어플리케이션에서도 같은 문제가 발생하였습니다.불필요한 요소 로딩 프로세스로 인해 발생하였습니다.
구코드
return (......
<NotificationDialog
show={notificationPayload !== null}
title={notificationPayload?.title}
.......
/>
);
NotificationDialog even notificationPayload !== null이 다시 표시됩니다.하지만 그것은 필요하지 않다.단순히 이 늘체크를 추가하고 늘일 경우 이 NotificationDialog를 렌더링하지 않도록 합니다.
고치다
return (......
{ notificationPayload !== null? <NotificationDialog
show={notificationPayload !== null}
title={notificationPayload?.title}
.......
/> : null }
);
반환해야 .<>{values}</>
ConvertDate를 Import해야 만 Import할 때문에것 .redux(useSelector) ConvertDate(ConvertDate) Import(Import)를 사용합니다그냥 함수를 사용해서 날짜랑 레독스 상태를 소품으로 넘길 수도 있었는데...
내가 가진 것:
<b>{ConvertDate({ date: post.dateTime })}</b>
내가 어떻게 고쳤는지:
<b>{<ConvertDate date={post.dateTime} />}</b>
많이 늦었지만 같은 오류 스택에 대한 경험을 공유하고자 합니다.
은 으로 일어났다useQuery
와 4인치useEffect
ReactJS
17.
여기 아름다운 토론이 하나 있습니다.
스택 트레이스:
react_devtools_backend.js:4026 Warning: React has detected a change in the order of Hooks called by Applicants. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks
Previous render Next render
------------------------------------------------------
1. useContext useContext
2. useContext useContext
3. useState useState
4. useRef useRef
5. useEffect useEffect
6. useRef useRef
7. useEffect useEffect
8. useContext useContext
9. useState useState
10. useRef useRef
11. useEffect useEffect
12. useRef useRef
13. useEffect useEffect
14. useState useState
15. useState useState
16. useState useState
17. useState useState
18. useState useState
19. useState useState
20. useContext useContext
21. useContext useContext
22. useContext useContext
23. useContext useContext
24. useEffect useEffect
25. useState useState
26. useCallback useCallback
27. useState useState
28. useLayoutEffect useLayoutEffect
29. useEffect useEffect
30. useDebugValue useDebugValue
31. useEffect useEffect
32. undefined useEffect
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
제가 래서이 the the the the the the the to 를 사용했기 되었습니다. VIPuseEffect
그 useQuery
api line을 callback line은 api callback line 。useEffect
before useQuery
모든 경고 스택트레이스가 해결되었습니다
도움이 됐으면 좋겠는데
언급URL : https://stackoverflow.com/questions/57397395/react-has-detected-a-change-in-the-order-of-hooks-but-hooks-seem-to-be-invoked
'programing' 카테고리의 다른 글
입력 필드의 텍스트 사용 안 함 7 워드프레스 연락처 (0) | 2023.02.26 |
---|---|
jq json 출력에서 열 제외 (0) | 2023.02.26 |
angularjs는 입력 유효성 검사에 실패할 때 폼 제출을 방지합니다. (0) | 2023.02.26 |
JSONObject를 맵으로 변환 (0) | 2023.02.26 |
워드프레스 플러그인 개발 - 이미지 사용 - 경로를 찾을 수 없습니다. (0) | 2023.02.26 |