npm i react-router-dom
: react-router와 redux를 약하게 연결시켜 주는 기능
아래 예제처럼 store와 route부분에 history를 연결해주면,
redux thunk안에서 withExtraArgument를 가져와서 history를 빼와서,
history로 페이지를 이동할 수 있게 해줌.
// src > history.js
// "./history"는 react-router-dom 설치시 함께 설치되는 내부 모듈,
import { createBrowserHistory } from "history";
const history = createBrowserHistory();
export default history;
// store.js
import history from "../history";
const store = createStore(
reducer,
composeWithDevTools(
applyMiddleware(thunk.withExtraArgument({ history }), promise)
)
);
// App.js
import history from "./history";
function App() {
return (
<Router history={history}>
<Route />
</Router>
);
}
// users.js (thunk이용하는 리듀서)
export function getUsersThunk() {
return async(dispatch, getState, { history }) => {
try {
console.log(history);
dispatch(getUsersStart()); // 로딩중
const res = await axios.get("")
dispatch(getUserSuccess(res.data)); // 데이터 가져오기 성공
history.push("/");
} catch (error) {
dispatch(getUsersFail(error)); // 실패
}
};
}
: react-router와 redux를 강하게 연결시켜 주는 기능
redux안에 reducer로 router를 통째로 연결하는 방법
npm i connected-react-router
// src > redux > modules > reducer.js(rootReducer)
import { connectRouter } from 'connected-react-router';
import history from "../../history";
const reducer = combineReducers({
todos,
filter,
users,
router: connectRouter(history)
});
export default reducer;
//src > redux > store.js
import history from "./history";
import { routerMiddleware } from 'connected-react-router';
const store = createStore(
reducer(history),
composeWithDevTools(
applyMiddleware(
thunk.withExtraArgument({ history }), promise,
routerMiddleware(history)
)
)
);
// App.js
import history from "../history";
import { ConnedtedRouter } from "connected-react-router";
function App() {
return (
<ConnectedRouter history={history}>
<Route />
</ConnectedRouter>
);
}
// src > pages > Hone.jsx
import { push } from "connected-react-router";
import { useDispatch } from "react-redux";
import { Link } from "react-router-dom";
export default function Home() {
const dispatch = useDispatch();
function click() {
dispatch(push("/todos");
}
return(
<div>
<h1>Home</h1>
<button onClick={click}>todos 로 이동</button>
</div>
);
안녕하세요 포스트 잘 읽어보았는데요
react 버전이 18 버전으로 업데이트 후에는
connected-react-router dependency가 설치되지않던데 어떻게 해결하셨나요?