티스토리 뷰
Redux를 쓰는 이유
1. props가 귀찮을때 사용한다.
2. state변경 관리할 떄 사용한다.
리액트 스타일 웹개발 : 컴포넌트 단위로 쪼개서 개발해준다.
앞서 배웟듯이 component는 html 덩어리. 쪼갠것
함수인데 html을 뱉는 함수 <div></div> <- 이런것
state를 만들어서 변수에 저장하고 props 통해서 내려준다.
이렇게 props로 계속 내려주기 귀찮을때 사용하는 라이브러리 = Redux
Redux를 설치한 후 state를 저장해두면. props로 내려줄 필요없이 모든 컴포넌트들이 꺼내다가 사용가능하다
index.js
밑에 형식은 그냥 문법일뿐이다.
이해하려고하지말고 사용해도 무관하다.
import {Provider} from 'react-redux';
import {createStore} from 'redux';
const 체중 = 100 //state 맘대로 보관가능
function reducer(state = 체중, action){
return state
}
let store = createStore(reducer)
reactDOM.render(
<Provider store = {store}>
<App/>
</Provider>
)
컴포넌트 파일에서 체중을 어떻게 가져다 쓰나?
app.js
import './App.css';
import {useSelector} from 'react-redux'
function App(){
const 꺼내온거 = useSelector((state) => state ) //꺼내온거 = 100
return (
<div className = 'App'>
<p>님의 처참한 몸무게 : {꺼내온거} </p> //꺼내온거 = 100
</div>
)
}
export default App
- props없이 state 직접 꺼내다쓸수있고
- state관리하기용이하다
어떻게 보면 API를 만든다고 생각할수도 있다.
컴포넌트들은 수정요청을한다.
버그가 생겼을때 ? 누구 문제야!! 접니다 store.js
state수정 방법 Reducer
import {Provider} from 'react-redux';
import {createStore} from 'redux';
const 체중 = 100 //state 맘대로 보관가능
function reducer(state = 체중, action){
if(action.type === '증가'){
state++
return state
}else if(action.type === '감소'){
state--
return state
}else{
return stae
}
}
let store = createStore(reducer)
reactDOM.render(
<Provider store = {store}>
<App/>
</Provider>
)
컴포넌트에서 수정요청하려면?
import './App.css';
import {useSelector} from 'react-redux'
function App(){
const 꺼내온거 = useSelector((state) => state ) //꺼내온거 = 100
const dispatch = useDispatch()
return (
<div className = 'App'>
<p>님의 처참한 몸무게 : {꺼내온거} </p> //꺼내온거 = 100
<button onClick={()=>{dispatch({type : '증가'}) }}>더하기</button>
</div>
)
}
export default App