Programing

리액션 후크에 있는 많은 소스에서 가져온 경우 리액션을 방지하는 방법

c10106 2022. 3. 29. 21:33
반응형

리액션 후크에 있는 많은 소스에서 가져온 경우 리액션을 방지하는 방법

사용하고 있다.react hooksRact Native로.내 문제는 의 기능이useState상태를 초기화하면 다시 초기화된다.그래서 만약 내가 아래와 같이 state를 설정한다면

    const [A, setA] = useState(false);
    const [B, setB] = useState(false);
    const [C, setA] = useState(false);

    // ...

    const testFunc = () => {
        setA(true);
        setB(true);
        setC(true);
    }


편집된 나는 예시가 틀렸다고 생각한다.여기 또 다른 예가 있다.

const useFetch(coords) {
    const [example, setExample] = useState([])
    const [checker, setChecker] = useState(false);

    const fetchData = () => {
        axios.fetch(`url+${coords.latitue}+${coords.longitude}`).then(){
            setExample(res.data());
            setChecker(true);
        }
    }

    useEffect(() => {
        fetchData();
    }, [coords])

    return example;
}

const useLocation = () => {
    ...
    return coords;
}

const App = () => {
    const coords = useLocation();
    const example = useFetch(coords); // example is undefined.
    const [data, setData] = useState(example); // data is undefined.
}

설정 기능을 사용하는 만큼 많은 리렌더를 발생시킨다.이게 자연스런 일인가?이 렌더링을 만들지 않으려면 설정 기능을 여러 번 사용할 수 없는지요?

너는 그것을 단도직입적으로 할 수 없다.나는 그것에 대한 두 가지 해결책을 너에게 제안할 것이다.

해결책 1: 상태를 하나의 객체에 결합한다.

const [value, setValue] = useState({A: false, B: false, C: false});

// ...

const testFunc = () => {
    setValue({A: true, B: true, C: true});
}

해결책 2: 또 다른 해결책은useReducer.

const [state, setState] = useReducer(
  (state, newState) => ({...state, ...newState}),
  {A: false, B: false, C: false}
);

// ...

const testFunc = () => {
    setState({A: true, B: true, C: true});
}

여기에 다른 예제를 적용했습니다 https://stackblitz.com/edit/react-usestate-wcjshg

이것이 너에게 도움이 되길 바래!

반응 기반 이벤트 외부에서 트리거된 경우 대응은 상태 업데이트를 배치하지 않는다.즉, 상태 업데이트를 패치하려면 다음과 같은 이벤트 핸들에 해당 업데이트를 래핑해야 함onClick.

로컬 구성 요소 상태가 트라이벌 상태가 아니거나 이벤트 핸들러를 사용할 수 없는 경우useReducer그 안에 상태 업데이트를 배치할 수 있기 때문에.

이것은 정상적인 반응 동작으로 보인다.클래스 구성 요소에서 setState()를 여러 번 호출하는 경우에도 동일한 방식으로 작동한다.

React는 버튼 클릭이나 입력 변경과 같은 React 기반 이벤트 내에서 트리거되는 경우 현재 상태 업데이트를 배치한다.setTimeout()과 같이 Resact 이벤트 핸들러 외부에서 트리거되는 경우 업데이트를 배치하지 않는다.

내 생각에 항상 이벤트를 일괄 처리할 장기 계획이 있는 것 같아. 하지만 세부사항은 확실하지 않아.

출처: https://github.com/facebook/react/issues/14259#issuecomment-439632622 https://github.com/facebook/react/issues/14259#issuecomment-468937068

다른 답변에 명시된 바와 같이, 반응 기반 이벤트 외부에서 트리거되는 경우 반응 상태 업데이트를 배치하지 않는다(In).then예를 들어), 해결책 중 하나는 한 개체에서 상태를 병합하고 setState를 한 번 호출하는 것이다.하지만 만약 당신이 당신의 상태를 분리시키고 싶다면, 해결책은ReactDOM.unstable_batchedUpdates다음과 같이:

    const fetchData = () => {
        axios.fetch(`url+${coords.latitue}+${coords.longitude}`).then(() => {
            ReactDOM.unstable_batchedUpdates(() => {
                setExample(res.data());
                setChecker(true);
            });
        });
    }

여기 댄 아브라모프가 추천함

참조URL: https://stackoverflow.com/questions/57864835/how-to-prevent-re-render-if-fetch-from-many-sources-in-react-hooks

반응형