반응형
저장 상태 변경 시 React-redux 구성 요소가 다시 렌더링되지 않음
오늘은 리액션과 리덕스를 배우려고 합니다만, 상태 변화 후에 컴포넌트를 강제로 리렌더 하는 방법을 알 수 없습니다.
코드는 다음과 같습니다.
const store = createStore(loginReducer);
export function logout() { return {type: 'USER_LOGIN'} }
export function logout() { return {type: 'USER_LOGOUT'} }
export function loginReducer(state={isLogged:false}, action) {
switch(action.type) {
case 'USER_LOGIN':
return {isLogged:true};
case 'USER_LOGOUT':
return {isLogged:false};
default:
return state;
}
}
class App extends Component {
lout(){
console.log(store.getState()); //IT SHOW INITIAL STATE
store.dispatch(login());
console.log(store.getState()); //IT SHOWS THAT STATE DID CHANGE
}
////THIS IS THE PROBLEM,
render(){
console.log('rendering')
if(store.getState().isLogged){
return (<MainComponent store={store} />);
}else{
return (
<View style={style.container}>
<Text onPress={this.lout}>
THE FOLLOWING NEVER UPDATE :( !!{store.getState().isLogged?'True':'False'}</Text>
</View>
);
}
}
업데이트를 트리거할 수 있는 유일한 방법은
store.subscribe(()=>{this.setState({reload:false})});
컴포넌트의 업데이트 상태를 수동으로 트리거하여 강제로 재렌더를 실행합니다.
하지만 스토어와 컴포넌트 상태를 어떻게 링크할 수 있을까요?
컴포넌트는 상태 또는 소품이 변경된 경우에만 재렌더됩니다.this.state 또는 this.props에 의존하지 않고 렌더 함수 내에서 직접 스토어 상태를 가져옵니다.
그 대신에,connect
애플리케이션 상태를 컴포넌트 소품에 매핑합니다.컴포넌트 예:
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
export class App extends React.Component {
constructor(props, context) {
super(props, context);
}
render() {
return (
<div>
{this.props.isLoggedIn ? 'Logged In' : 'Not Logged In'}
</div>
);
}
}
App.propTypes = {
isLoggedIn: PropTypes.bool.isRequired
};
function mapStateToProps(state, ownProps) {
return {
isLoggedIn: state.isLoggedIn
};
}
export default connect(mapStateToProps)(App);
이 매우 단순한 예에서는 스토어의 isLoggedIn 값이 변경되면 컴포넌트의 대응하는 프로포트가 자동으로 갱신되어 렌더링됩니다.
시작하는데 도움이 되는 react-prox 문서를 읽는 것이 좋습니다.https://redux.js.org/basics/usage-with-react
나는 불량 환원제를 썼기 때문에 결국 여기에 오게 되었다.나는 다음을 가지고 있었다.
const reducer = (state=initialState, action) => {
switch (action.type) {
case 'SET_Q':
return Object.assign(state, { // <- NB no {}!
q: action.data,
})
default:
return state;
}
}
필요:
const reducer = (state=initialState, action) => {
switch (action.type) {
case 'SET_Q':
return Object.assign({}, state, { // <- NB the {}!
q: action.data,
})
default:
return state;
}
}
언급URL : https://stackoverflow.com/questions/38678255/react-redux-component-does-not-rerender-on-store-state-change
반응형
'programing' 카테고리의 다른 글
React를 사용하여 인라인 글꼴 크기 스타일 생성JS (0) | 2023.02.26 |
---|---|
MySQL이 계속 크래시되다 (0) | 2023.02.26 |
엔티티 클래스 이름이 밑줄이 있는 SQL 테이블 이름으로 변환됩니다. (0) | 2023.02.26 |
Maven을 통해 Spring Boot에서 활성 프로파일 구성 (0) | 2023.02.26 |
리액트 컴포넌트 'displayName'의 용도는 무엇입니까? (0) | 2023.02.26 |