useEffect 내의 Redx 저장소에서 상태 가져오기 반응
Redux 스토어에서 상태를 얻는 올바른 방법은 무엇입니까?useEffect후크?
useEffect(() => {
const user = useSelector(state => state.user);
});
현재 상태를 파악하려고 합니다.useEffect단, 이 명령어를 사용할 수 없습니다.useSelector이 경우 다음과 같은 오류가 발생하므로 콜합니다.
Invariant Violation: Hooks can only be called inside the body of a function component.
나는 왜 그런지 알 것 같아. 왜냐하면 그것은 갈고리의 기본 규칙 중 하나를 어기기 때문이야.
Redux 문서의 예제를 검토해보니 이 문서에서는 다음 예제를 사용하고 있는 것 같습니다.selectors.js현재 상태를 수집하는 파일입니다만, 이 참조에서는,mapStateToProps더 이상 필요없다는 걸 깨달았어요
getter 함수를 만들 필요가 있습니까?이 함수는 다음 명령어 내에서 호출해야 합니다.useEffect후크?
추가되는 것을 잊지 마세요.user에 대한 의존으로서useEffect그렇지 않으면 효과가 업데이트되지 않습니다.
const user = useSelector(state => state.user);
useEffect(() => {
// do stuff
}, [user]);
를 배치할 수 있습니다.useSelector다른 후크와 함께 컴포넌트의 상부에 있습니다.
const MyComponent = () => {
...
const user = useSelector(state => state.user);
...
}
그러면 에 접속할 수 있습니다.user내면에useEffects.
2개의 useEffects를 사용하여 사용자(또는 이 경우 currUser)를 갱신할 수 있습니다.
const user = useSelector(state=>state.user);
const [currUser, setCurrUser] = useState(user);
useEffect(()=>{
dispatch(loadUser());
}, [dispatch]);
useEffect(()=>{
setCurrUser(user);
}, [user]);
해당 개체를 표시 및 조작하려면 currUser를 사용해야 합니다.
두 가지 선택이 있습니다.
1 - 스토어에서 값이 1회 또는 'n'회만 필요한 경우 useEffect 호출 시 redex에서 사용자 상태에 발생할 수 있는 변경을 듣고 싶지 않은 경우 이 방법을 사용합니다.
//import the main store file from where you've used createStore()
import {store} from './store' // this will give you access to redux store
export default function MyComponent(){
useEffect(() =>{
const user = store.getState().user;
//...
},[])
}
2 - 사용자 상태에 발생할 수 있는 변경을 듣고 싶은 경우 권장되는 답변은 다음과 같습니다.
const MyComponent = () => {
//...
const user = useSelector(state => state.user);
useEffect(() => {
//...
},[])
//...
}
const tournamentinfofromstore=useSelector(state=>state.tournamentinfo)
useEffect(() => {
console.log(tournamentinfofromstore)
}, [tournamentinfofromstore])
따라서 문제는 useEffect 내에서 상태를 변경하여 재렌더를 발생시키고 다시 그 컴포넌트가 다른 컴포넌트에 데이터를 전달하고 있는 경우 useEffect가 "&"로 불리게 되면 무한 루프가 발생한다는 것입니다.또, 그 데이터를 자컴포넌트 상태에서도 보존하고 있기 때문에, 재렌더링이 발생하고, 그 결과 무한 루프 상태가 됩니다.!!
권장되지는 않지만,store컴포넌트에 직접 접속하여useEffect.
먼저 수출해야 합니다.store생성원부터 시작합니다.
import invoiceReducer from './slices/invoiceSlice';
import authReducer from './slices/authSlice';
export const store = configureStore({
reducer: {
invoices: invoicesReducer,
auth: authReducer,
},
});
그런 다음 에 Import할 수 있습니다.React Component또는 심지어function를 사용합니다.
import React, { useEffect } from 'react';
import { store } from './store';
const MyComponent = () => {
useEffect(()=> {
const invoiceList = store.getState().invoices
console.log(invoiceList)
}, [])
return (
<div>
<h1>Hello World!</h1>
</div>
)
}
export default MyComponent
- 학습할 수 있습니다.
API위해서Store이 안에. - 또, 이 어프로치가 추천되지 않는 이유도 알 수 있습니다.
- 또는 다음 웹 사이트를 사용하고자 하는 경우
redux store바깥에react component, 이 블로그의 투고를 봐 주세요.
@Motomoto의 답장에 덧붙여.useEffect를 사용하기 전에 로드해야 하는 저장소에 의존하는 경우가 있습니다.이 경우 상태가 정의되지 않은 경우 단순히 복귀할 수 있습니다.스토어가 로드되면 useEffect가 다시 렌더링됩니다.
const user = useSelector(state => state.user);
useEffect(() => {
if(user === undefined){
return}else{
// do stuff
}}, [user]);
같은 문제가 있습니다.useSelector의 문제는 훅에 호출할 수 없기 때문에 액션을 적절히 갱신할 수 없다는 것입니다.그래서 useSelector 변수를 useEffect에 의존하여 사용했더니 문제가 해결되었습니다.
const finalImgData_to_be_assigned = useSelector((state) => state.userSelectedImg);
useEffect(()=>{
console.log('final data to be ready to assign tags : ', finalImgData_to_be_assigned.data);
}, [finalImgData_to_be_assigned ])
언급URL : https://stackoverflow.com/questions/58159108/react-get-state-from-redux-store-within-useeffect
'programing' 카테고리의 다른 글
| PLS-00201: 식별자를 선언해야 합니다. (0) | 2023.03.25 |
|---|---|
| ObjectResult와 JsonResult의 차이점 (0) | 2023.03.20 |
| Oracle SQL 스키마의 모든 테이블을 나열하려면 어떻게 해야 합니까? (0) | 2023.03.20 |
| Backbone.js 모델 데이터를 저장하는 방법 (0) | 2023.03.20 |
| WordPress wp_head - 새로운 스크립트 파일을 상단에 추가하려면 어떻게 해야 합니까? (0) | 2023.03.20 |