prosource

클래스 컴포넌트에서 react-redux useSelector를 사용하려면 어떻게 해야 합니까?

probook 2023. 3. 9. 22:08
반응형

클래스 컴포넌트에서 react-redux useSelector를 사용하려면 어떻게 해야 합니까?

나는 리액션에서 처음이고 레덕스를 배우려고 한다.클래스 내의 스토어에 액세스 하고 싶은데, 수업중에 후크를 사용할 수 없다는 에러가 표시됩니다.

이 코드를 기능적으로 사용하면(YouTube 튜토리얼에서 본 것처럼) 문제없이 동작합니다.여기 가게 카운터가 있어요.

 function App() {
      const counter = useSelector(state => state.counter);
    
      return <div>{counter}</div>;
    }

하지만 수업 중에 이걸 하고 싶을 때 수업 중에 훅을 사용할 수 없다는 오류가 발생합니다.

그러면 클래스 컴포넌트에서 useSelector 또는 useDispatch 중 하나를 사용하여 스토어에 액세스하려면 어떻게 해야 합니까?

@Ying Zuo가 말했듯이 이 메서드는 기능 컴포넌트에서만 작동합니다.이 문제를 해결하려면:

다음 행 대신:

const counter = useSelector(state => state.counter);

카운터 상태는 다음과 같이 정의합니다.

const mapStateToProps = state => ({
    counter: state.counter
});

디스패치에는 다음과 같이 사용해야 합니다.

const mapDispatchToProps = () => ({ 
    increment, 
    decrement
});

마지막에는 모든 것을 다음과 같이 결합합니다.

export default connect(
    mapStateToProps,
    mapDispatchToProps()
)(App);

Import하는 것을 잊지 마세요.increment그리고.decrement에서action그리고.connect에서react-redux모듈.

useSelector그리고.useDispatch리액트 훅은 기능 컴포넌트에서만 동작합니다.

https://reactjs.org/docs/hooks-overview.html#but-what-is-a-hook

리액트 훅을 사용하면 대부분의 컴포넌트를 기능 컴포넌트로 작성할 수 있습니다.클래스 기반 컴포넌트를 작성해야 하는 경우connect리액트 리액트 리액트 리액트 리액트 리플렉스

https://blog.logrocket.com/react-redux-connect-when-and-how-to-use-it-f2a1edab2013/

class App extends Component {
    constructor(props){
        super(props)
        this.state = {
            reduxState : {}
        }
    }
    DummyView = () => {
        const reducer = useSelector(state => state.reducer)
        useEffect(() => {
            this.setState({
                reduxState : reducer
            })
        }, [])
        return null
    }
    render(){
        return(
            <this.DummyView/>
        )
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

언급URL : https://stackoverflow.com/questions/57135857/how-can-i-use-react-redux-useselector-in-class-component

반응형