yarn add @reduxjs/toolkit
import { createSlice } from "@reduxjs/toolkit";
import { removeNumber } from "../modules/counter";
// 초기 상태값
const initialState = {
number: 0,
};
const counterSlice = createSlice({
name: "counter",
initialState: initialState,
reducers: {
addNumber: (state, action) => {
state.number = state.number + action.payload;
},
removeNumber: (state, action) => {
state.number = state.number - action.payload;
},
},
});
export const { addNumber, removeNumber } = counterSlice.actions;
export default counterSlice.reducer;
configStore.js
// import { combineReducers, createStore } from "redux";
// import counter from "../modules/counter";
import { configureStore } from "@reduxjs/toolkit";
import counterSlice from "../slices/counterSlice";
// 1. rootReducer을 만든다.
const rootReducer = combineReducers({
counter,
});
// // 2. store을 조합
// const store = createStore();
const store = configureStore({
reducer: { counterSlice },
});
// 3,. 만든 store 내보내기
export default store;
slice파일에서 actions와 reducer을 내보내준다
여러페이지를 이동하는 방법
import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Home from "../pages/Home";
import Works from "../pages/Works";
import About from "../pages/About";
const Router = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/works" element={<Works />} />
</Routes>
</BrowserRouter>
);
};
export default Router;
import React from "react";
import Router from "./shared/Router";
const App = () => {
return (
<div>
<Router />
</div>
);
};
export default App;
import React from "react";
import { useNavigate } from "react-router-dom";
const Home = () => {
const navigate = useNavigate();
return (
<div>
<h1>Home컴포넌트입니다.</h1>
<button
onClick={() => {
navigate("/works");
}}
>
works로 이동
</button>
</div>
);
};
export default Home;
a 태그를 사용하지 않고 link태그를 사용해야만한다. 새로고침이 되면 안되기 때문.
import React from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
const Works = () => {
const navigate = useNavigate();
const location = useLocation();
console.log("location", location);
return (
<div>
<h1>Works페이지입니다.</h1>
<div>현재 페이지 : {location.pathname.slice(1)}</div>
{/* <button
onClick={() => {
navigate("/");
}}
>
Home로 이동
</button> */}
<Link to="/contact">contact페이지로 이동하기</Link>
</div>
);
};
export default Works;