React-Native Redux 설치
- Front End/React-Native
- 2020. 3. 24. 20:36
> npm install redux
> npm install react-redux
설치는 굉장히 간단하다. 하지만 Redux를 처음 접한다면 상당히 어렵다.
Redux를 사용하는 가장 중요한 이유는 컴포넌트들의 상태를 공유하기 위함이다.
아래는 중요한 코드만 적어두겠다.
//**********************************************
******************** App.js ********************
************************************************//
... 생략 ...
import { createStore } from 'redux';
import { Provider } from 'react-redux';
const initialState = {
counter: 0
}
const reducer = (state=initialState, action) => {
switch(action.type){
case 'INCREASE_COUNTER': {
return{counter:state.counter+1}
}
case 'DECREASE_COUNTER':
return{counter:state.counter-1}
}
return state
}
const store = createStore(reducer)
class App extends React.Component {
render() {
return (
<Provider store={store}>
<HomeScreen/>
</Provider>
);
}
}
... 생략 ...
//*******************************************************
******************** HomeScreen.js ********************
*******************************************************//
... 생략 ...
import { connect } from 'react-redux';
class HomeScreen extends Component {
render () {
return (
<View>
<Text>{this.props.counter}</Text>
<TouchableOpacity onPress={()=>{this.props.increaseCounter()}}>
<Text>Increase</Text>
</TouchableOpacity>
</View>
);
}
}
const mapStateToProps = state => {
return {
counter: state.counter
}
}
const mapDispatchToProps = dispatch => {
return {
increaseCounter : () => dispatch({type:'INCREASE_COUNTER'}),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(HomeScreen);
... 생략 ...
'Front End > React-Native' 카테고리의 다른 글
Firebase - Functions (0) | 2020.05.17 |
---|---|
React-Native-Image-Picker (0) | 2020.05.04 |
react-native-firebase (0) | 2020.04.05 |
React-Navigation (0) | 2020.03.15 |
[React-Native] Getting Started (Windows) (0) | 2020.03.03 |
이 글을 공유하기