import { legacy_createStore as createStore } from 'redux'; //스토어 라이브러리
import { Provider } from 'react-redux';
const rdata = {name : '홍길동', age : 20}
function reducer(state = rdata, action) {
return state
}
function reducer(현재상태, 컴포넌트액션처리변수){return state}
const store = createStore(reducer);
const store = createStore(호출함수);
root.render(
<React.StrictMode>
<Provider store={store}> {/* 스토어 사용 범위 지정 */}
<App />
</Provider>
</React.StrictMode>
);
app.js 파일
import { useSelector } from 'react-redux';
import './App.css';
function App() {
//useSelector 이용하여 store에 저장된 reducer 함수의 state값 가져오기
const state = useSelector(state => state);
return (
<div >
<h1>이름 : {state.name}</h1>
<h1>나이 : {state.age}</h1>
</div>
);
}
export default App;
index,js에서 스토어 호출 함수에 조건 추가
function reducer(state = rdata, action) {
if (action.type = 'plus') {
return {
name: state.name, age: state.age + 1, addr: state.addr
}
}
return state
}
action.type 이 plus라면 age만 나이를 더먹음 ㅜㅜ
import { useDispatch, useSelector } from 'react-redux';
import './App.css';
import Child1 from './components/Child1';
function App() {
//useSelector 이용하여 store에 저장된 reducer 함수의 state값 가져오기
const state = useSelector(state => state);
const dispatch = useDispatch();
return (
<div >
<h1>[App]이름 : {state.name}</h1>
<h1>[App]나이 : {state.age}</h1>
<button type='button' onClick={() => dispatch({ type: 'plus' })}>age ++</button>
<hr />
</div>
);
}
export default App;
const dispatch = useDispatch();
선언하고 버튼을 클릭하면 onClick={() => dispatch({ type: 'plus' })} 실행되도록
이제 버튼을 누르면 금새 나이를 먹음