클래스 컴포넌트에서 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
'prosource' 카테고리의 다른 글
사용자/게스트가 WooCommerce에서 특정 제품을 구입했는지 확인합니다. (0) | 2023.03.09 |
---|---|
스프링 @프로퍼티 자동배선 vs 컨스트럭터 (0) | 2023.03.09 |
Redux 연결 컴포넌트는 재렌더 타이밍을 어떻게 알 수 있습니까? (0) | 2023.03.09 |
Material-UI에서 TextField의 밑줄을 삭제하려면 어떻게 해야 합니까? (0) | 2023.03.09 |
JSON API Wordpress가 App을 통해 업로드 시 피처링 이미지를 표시하지 않음 (0) | 2023.03.09 |