잘못된 후크 호출입니다.후크는 기능 구성 요소의 본체 내부에서만 호출할 수 있습니다.
React를 사용하여 테이블에 레코드를 표시하려고 하는데 다음 오류가 발생했습니다.
잘못된 후크 호출입니다.후크는 기능 컴포넌트 본체 내부에서만 호출할 수 있습니다.이 문제는 다음 중 하나의 이유로 발생할 수 있습니다.
- React와 렌더러의 버전이 일치하지 않을 수 있습니다(React DOM 등).
- 후크 규칙을 어기고 있을 수 있습니다.
- 동일한 앱에 React 복사본이 두 개 이상 있을 수 있습니다. 이 문제를 디버깅하고 해결하는 방법에 대한 팁은 을 참조하십시오.
import React, {
Component
} from 'react';
import {
makeStyles
} from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
const useStyles = makeStyles(theme => ({
root: {
width: '100%',
marginTop: theme.spacing(3),
overflowX: 'auto',
},
table: {
minWidth: 650,
},
}));
class allowance extends Component {
constructor() {
super();
this.state = {
allowances: [],
};
}
componentWillMount() {
fetch('http://127.0.0.1:8000/allowances')
.then(data => {
return data.json();
}).then(data => {
this.setState({
allowances: data
});
console.log("allowance state", this.state.allowances);
})
}
render() {
const classes = useStyles();
return ( <
Paper className = {
classes.root
} >
<
Table className = {
classes.table
} >
<
TableHead >
<
TableRow >
<
TableCell > Allow ID < /TableCell> <
TableCell align = "right" > Description < /TableCell> <
TableCell align = "right" > Allow Amount < /TableCell> <
TableCell align = "right" > AllowType < /TableCell>
<
/TableRow> <
/TableHead> <
TableBody > {
this.state.allowances.map(row => ( <
TableRow key = {
row.id
} >
<
TableCell component = "th"
scope = "row" > {
row.AllowID
} <
/TableCell> <
TableCell align = "right" > {
row.AllowDesc
} < /TableCell> <
TableCell align = "right" > {
row.AllowAmt
} < /TableCell> <
TableCell align = "right" > {
row.AllowType
} < /TableCell> <
/TableRow>
))
} <
/TableBody> <
/Table> <
/Paper>
);
}
}
export default allowance;
이 문제는 제가 사용했을 때 발생했습니다.npm link
도서관을 cra
여기서 답을 찾았어요.그 말은 말 그대로:
이 문제는 npm 링크 또는 동등한 링크를 사용하는 경우에도 발생할 수 있습니다.이 경우 번들러는 응용 프로그램 폴더와 라이브러리 폴더에 있는 두 개의 응답을 "확인"할 수 있습니다.'myapp'과 'mylib'가 형제 폴더라고 가정할 때, 한 가지 가능한 수정 방법은 'mylib'에서 'npm link ../myapp/node_modules/react'를 실행하는 것입니다.그러면 라이브러리가 응용 프로그램의 React 복사본을 사용하게 됩니다.
명령어를 합니다.npm link <path_to_local_library>/node_modules/react
내 예: " )npm link ../../libraries/core/decipher/node_modules/react
문제가 해결되었습니다.
후크는 React 함수에서만 호출할 수 있습니다.자세한 것은 이쪽.
하면 돼요.Allowance
클래스 컴포넌트를 기능 컴포넌트로 설정합니다.
const Allowance = () => {
const [allowances, setAllowances] = useState([]);
useEffect(() => {
fetch("http://127.0.0.1:8000/allowances")
.then(data => {
return data.json();
})
.then(data => {
setAllowances(data);
})
.catch(err => {
console.log(123123);
});
}, []);
const classes = useStyles();
return ( <
Paper className = {
classes.root
} >
<
Table className = {
classes.table
} >
<
TableHead >
<
TableRow >
<
TableCell > Allow ID < /TableCell> <
TableCell align = "right" > Description < /TableCell> <
TableCell align = "right" > Allow Amount < /TableCell> <
TableCell align = "right" > AllowType < /TableCell> <
/TableRow> <
/TableHead> <
TableBody > {
allowances.map(row => ( <
TableRow key = {
row.id
} >
<
TableCell component = "th"
scope = "row" > {
row.AllowID
} <
/TableCell> <
TableCell align = "right" > {
row.AllowDesc
} < /TableCell> <
TableCell align = "right" > {
row.AllowAmt
} < /TableCell> <
TableCell align = "right" > {
row.AllowType
} < /TableCell> <
/TableRow>
))
} <
/TableBody> <
/Table> <
/Paper>
);
};
export default Allowance;
React를 반환하는 Arrow 함수를 호출하여 "export default"를 사용할 수 있습니다.구성 요소를 재료에 통과시킴으로써 구성 요소UI 클래스 오브젝트 소품은 컴포넌트 렌더링() 내에서 사용됩니다.
class AllowanceClass extends Component{
...
render() {
const classes = this.props.classes;
...
}
}
export default () => {
const classes = useStyles();
return (
<AllowanceClass classes={classes} />
)
}
저에게 오류는 함수 useState를 호출하는 것입니다.기본 내보내기 함수 외부에 있습니다.
리액트 모든 .use
이름을 바꿔서const useStyles
시작도 하지 않는 다른 어떤 것으로도use
const myStyles
가도 돼
업데이트:
makeStyles
훅 api이므로 내부 클래스에서는 사용할 수 없습니다.스타일 컴포넌트 API를 사용할 수 있습니다.여기를 참조해 주세요.
.<Provider store={store}>
훅 콜이 무효가 되어도 문제가 발생합니다.그 때문에, 그 폴더에 react-redux 소프트웨어를 인스톨 하지 않았던 것을 문득 깨달았습니다.
저는 이 소프트웨어를 다른 프로젝트 폴더에 설치했기 때문에, 이 폴더에도 필요한 줄은 몰랐습니다.인스톨 하면, 에러는 해소됩니다.
또한 이 할 수 .「 react - redux 」를useDispatch가 됩니다.이 오류는 다음과 같습니다.
const dispatch = useDispatch
음음음:
const dispatch = useDispatch();
괄호를 을 잊지 (문장: 「」를 참조해 주세요.)
redux를 사용하는 사용자:
class AllowanceClass extends Component{
...
render() {
const classes = this.props.classes;
...
}
}
const COMAllowanceClass = (props) =>
{
const classes = useStyles();
return (<AllowanceClass classes={classes} {...props} />);
};
const mapStateToProps = ({ InfoReducer }) => ({
token: InfoReducer.token,
user: InfoReducer.user,
error: InfoReducer.error
});
export default connect(mapStateToProps, { actions })(COMAllowanceClass);
이것을 패키지에 추가합니다.json
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
출처 : https://robkendal.co.uk/blog/2019-12-22-solving-react-hooks-invalid-hook-call-warning
공유 라이브러리 간에 서로 다른 버전의 반응이 문제인 것 같습니다(16과 17). 둘 다 16으로 변경되었습니다.
클래스 컴포넌트를 후크로 변환할 수 있지만, Material v4에는 Styles HOC가 있습니다.https://material-ui.com/styles/basics/ #sys-order-component-api 이 HOC을 사용하면 코드를 변경하지 않고 유지할 수 있습니다.
훅을 사용하기 시작한 지 얼마 되지 않아 함수 내 useEffect를 호출할 때 위의 경고가 표시되었습니다.
그 후 다음과 같이 useEffect를 함수 외부로 이동해야 합니다.
const onChangeRetypePassword = async value => {
await setRePassword(value);
//previously useEffect was here
};
//useEffect outside of func
useEffect(() => {
if (password !== rePassword) {
setPasswdMismatch(true);
}
else{
setPasswdMismatch(false);
}
}, [rePassword]);
그것이 누군가에게 도움이 되기를 바랍니다!
을 '컴포넌트명을 전달하고 .FlatList
의 »renderItem
기능 대신 소품.제 컴포넌트가 기능 컴포넌트이기 때문에 조금 전에 동작하고 있었습니다만, 후크를 추가했을 때 고장이 났습니다.
이전:
<FlatList
data={memberList}
renderItem={<MemberItem/>}
keyExtractor={member => member.name.split(' ').join('')}
ListEmptyComponent={
<Text style={{textAlign: 'center', padding: 30}}>
No Data: Click above button to fetch data
</Text>
}
/>
그 후:
<FlatList
data={memberList}
renderItem={({item, index}) => <MemberItem item={item} key={index} />}
keyExtractor={member => member.name.split(' ').join('')}
ListEmptyComponent={
<Text style={{textAlign: 'center', padding: 30}}>
No Data: Click above button to fetch data
</Text>
}
/>
제 경우, 이 코드의 한 줄에 불과합니다.이 때문에, App.js에 있는 코드로 인해, 디버깅에 10시간을 할애할 수 없게 되었습니다.리액트 네이티브와 엑스포는 나에게 이것을 알려줄 수 없었다.StackOverflow와 github에 있는 모든 것을 했고, 이를 해결하기 위한 리액트 페이지도 지속되었습니다.나는 범인을 잡기 위해 조금씩 코드를 분해해야 했다.
**const window = useWindowDimensions();**
다음과 같이 배치되어 있습니다.
import * as React from 'react';
import { Text, View, StyleSheet, ImageBackground, StatusBar, Image, Alert, SafeAreaView, Button, TouchableOpacity, useWindowDimensions } from 'react-native';
import Constants from 'expo-constants';
import Whooksplashscreen11 from './Page1';
import Screen1 from './LoginPage';
import Loginscreen from './Login';
import RegisterScreen1 from './register1';
import RegisterScreen2 from './register2-verifnum';
import RegisterScreen3 from './register3';
import RegisterScreen4 from './register4';
import RegisterScreen5 from './register5';
import RegisterScreen6 from './register6';
import BouncyCheckbox from "react-native-bouncy-checkbox";
import LocationPermission from './LocationPermission.js'
import Selfieverif1 from './selfieverif1'
import Selfieverif2 from './selfieverif2'
import AddPhotos from './addphotos'
// You can import from local files
import { useFonts } from 'expo-font';
// or any pure javascript modules available in npm
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
//FontAwesome
import { library } from '@fortawesome/fontawesome-svg-core'
import { fab, } from '@fortawesome/free-brands-svg-icons'
import { faCheckSquare, faCoffee, faFilter, faSearch, } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome'
import Icon from "react-native-vector-icons/FontAwesome5";
import MyTabs from './swipepage'
library.add(fab, faCheckSquare, faCoffee, faFilter, faSearch,);
const window = useWindowDimensions();
const Stack = createNativeStackNavigator();
function App() {
return ( ....
)}
저 같은 경우에는 창문에 mdbreact를 사용하려고 했습니다.설치는 되었지만 위의 오류가 발생하였습니다.다시 설치해야 했고 모든 게 괜찮았어요.두 번은 개미도서관에서 일어난 일이었어
mobx 를 , 가 mobx 로 랩 있는 할 수 .observer
에는 꼭 사용하세요, 사용법', '어느 정도', '어느 정도 사용법'을 사용해 보세요.mobx-react
.0.0 이전 이 에러로 인해 합니다.이전 버전에서는 기능 컴포넌트가 커버된 클래스로 변환되어 모든 훅이 실패하고 이 오류가 발생합니다.
답변은 여기를 참조하십시오.응답 후크 Mobx: 비활성 후크 호출. 후크는 기능 구성 요소의 본체 내부에서만 호출할 수 있습니다.
제 경우엔package-lock.json
그리고.node_modules
재인스톨을 실시해, 정상적으로 동작합니다.
// project structure
root project
- package-lock.json
- package.json // all dependencies are installed here
- node_modules
-- second project
-- package-lock.json
-- package.json
"dependencies": {
"react": "file:../node_modules/react",
"react-dom": "file:../node_modules/react-dom",
"react-scripts": "file:../node_modules/react-scripts"
},
-- node_modules
이 문제는 이전에도 일어났고, 위와 같은 순서로 해결되었기 때문에, 애초에 무엇이 문제의 원인인지 알 수 없습니다.
나는 비슷한 문제에 부딪혔지만, 나의 상황은 약간 긴장된 경우였다.
인정된 답변은 대부분의 사람들에게 효과가 있을 것입니다.그러나 라듐을 사용하는 기존 리액트 코드에서 리액트 훅을 사용하는 다른 사람들은 라듐을 사용하는 경우 훅이 회피책 없이는 작동하지 않는다는 점에 유의하십시오.
제 경우 다음과 같이 컴포넌트를 내보내고 있었습니다.
// This is pseudocode
const MyComponent = props => {
const [hookValue, setHookValue] = useState(0);
return (
// Use the hook here somehow
)
}
export default Radium(MyComponent)
그것을 제거하다Radium
로부터의 포장지export
내 문제를 해결했어Radium을 사용해야 하는 경우 클래스 컴포넌트와 그 라이프 사이클 기능에 의존하는 것이 더 쉬운 해결책이 될 수 있습니다.
이게 적어도 한 사람만이라도 도움이 됐으면 좋겠어요.
프론트 엔드 작업이 자체 폴더에 있는 경우 백엔드 폴더가 아닌 해당 폴더 내에 @material-ui/core @material-ui/icon을 설치해야 할 수 있습니다.
npm i @material-ui/core @material-ui/icons
제 경우 Stack Navigator가 있는 App.js에서 네비게이션을 사용하여 모든 화면을 할당했습니다.그것이 있으면 아래 줄을 삭제해 주세요.
const navigation = useNavigation()
위의 모든 것이 동작하지 않는 경우, 특히 큰 사이즈의 의존성이 있는 경우(내 경우와 같이), 빌드 및 로딩 모두 최소 15초가 걸리기 때문에 지연으로 인해 "Invalid hook call"이라는 잘못된 메시지가 나타난 것 같습니다.따라서 테스트 전에 빌드가 완료되었는지 확인할 수 있습니다.
에러를 검출했습니다.해결 방법을 찾았습니다.
어떤 이유에선지 2개가 있었다.onClick
내 태그에 속성이 있습니다.사용자 또는 일부 사용자의 커스텀 컴포넌트를 사용할 때는 주의해 주십시오.이들 중 일부 컴포넌트는 이미 사용되고 있을 수 있습니다.onClick
기여하다.
를 설치하지 않고 종속성을 사용하는 경우에도 발생합니다.프로젝트에서 누락되었을 때 '@material-ui/icons/'에서 메뉴아이콘에 전화를 걸었을 때 생각이 났습니다.
이렇게 고쳤어요.node_modules 폴더와 파일 패키지를 가지고 있었습니다.json과 package-lock.json은 내 컴포넌트 폴더와 그것이 속한 프로젝트의 루트에 있습니다.그들이 속하지 않는 곳에서 삭제했어요.내가 뭘 했냐고 묻지 마 내가 잘못된 장소에서 NPM을 한 게 틀림없어.
제 경우 package-json에서 변경한 내용이 문제가 됩니다.
npm install react-redux
그것을 고치다
react-router-dom 을 사용하고 있는 경우는, 반드시 훅내의 useHistory() 를 호출해 주세요.
경로를 확인할 수 있습니다.Route의 컴포넌트(<Route path="/testpath") 대신 렌더를 사용하는 경우 렌더 = {(render)=><테스트 {...props} />} /> > 님의 컴포넌트에 적절한 소품을 전달하는 화살표 함수를 호출했습니다.
Import 문제 있음- 컴포넌트 및 자 컴포넌트에 대한 Import/Auto Import 실패가 오류였습니다.기능 클래스 vs 클래스 컴포넌트와는 관계가 없습니다.
- VS 코드 자동 가져오기가 작동하지 않는 경로를 지정할 수 있기 때문에 이 문제가 발생하기 쉽습니다.
{ MyComponent }
, 쓰입니다.export default
는 Import라고 해야 .import MyComponent
- 일부 컴포넌트가 폴더 내에서 경로의 숏컷으로 index.js를 사용하고 다른 컴포넌트에서는 Import가 중단될 수 있습니다.서도 자동 는 이 Import 폴더와 컴포넌트를 할 수 .
{TextComponent, ButtonComponent, ListComponent} from '../../common'
에러를 나타내는 파일내의 컴포넌트를 코멘트 해, 이것이 문제인지 아닌지를 테스트할 수 있습니다.
제 경우 npm 설치를 하기 위해 잘못된 디렉토리에 CD를 삽입한 것이 문제였습니다.라이브러리를 올바른 디렉토리에 다시 설치했는데 정상적으로 작동했어요!
는 이 .node_module
and and를 합니다.npm link
테스트용cra
(일부러)
으로 그것을 했다.node package
, 을.peerDependencies
"peerDependencies": {
"@types/react": "^16.8.6 || ^17.0.0",
"react": "^17.0.0",
"react-dom": "^17.0.0"
},
을 나의 것것 my my my my my에 한 후package.json
그후, 나는, 「」입니다.re-built
커스텀 패키지그리고 나서CRA
불었다, 불었다.node_modules
, renpm install
을 다시 .npm link <package>
프로젝트를 시작합니다.
다 고쳤어!
언급URL : https://stackoverflow.com/questions/56663785/invalid-hook-call-hooks-can-only-be-called-inside-of-the-body-of-a-function-com
'programing' 카테고리의 다른 글
numpy 배열이 비어 있는지 확인하려면 어떻게 해야 합니까? (0) | 2022.09.26 |
---|---|
execute()를 사용한 여러 SQL 문의 실행 (0) | 2022.09.26 |
가장 가까운 정수로 반올림 (0) | 2022.09.26 |
document.getElementById vs jQuery $() (0) | 2022.09.26 |
값과 키를 모두 PHP 어레이에 푸시하는 방법 (0) | 2022.09.26 |