แกะโค้ดตัวอย่าง redux-router5
Published in
1 min readJul 15, 2017
เจอว่า Router5 ทำเครื่องมือเอาไว้ไปรวมร่างกับ Redux ได้ง่ายขึ้น เลยเข้าไปนั่งอ่าน Example บทความนี้ตั้งใจจดเรื่องที่น่าสนใจเอาไว้อ่านเองทีหลัง
Source code อยู่นี่:
Store
import { router5Middleware, router5Reducer } from ‘redux-router5’;
- ใช้ package ชื่อ
redux-router5
router5Middleware
เอาไว้เปลี่ยน action เป็น router instruction (navigate
,cancel
,canActivate
,canDeactivate
)- สร้าง middleware ด้วยการบอกมันว่าต้องใช้ router ตัวไหนแบบนี้
router5Middleware(router)
router5reducer
เอาไว้เก็บข้อมูลเกี่ยวกับ route ลงใน store- ตอนนี้บังคับใช้ store key ว่า
route
เท่านั้น
ตัวอย่างโค้ด
function configureStore(router, initialState = {}) {
const createStoreWithMiddleware =
applyMiddleware(router5Middleware(router))(createStore);
const store = createStoreWithMiddleware(
combineReducers({
router: router5Reducer,
emails,
draft
}), initialState);
return store;
}
Actions
import { actions } from 'redux-router5';
- เอาไว้สร้าง action ที่เกี่ยวข้องกับการ routing
- ไม่ต้องใช้ก็ได้ เรียกจาก router ตรงๆก็ได้
naviagateTo(routeName, params, options)
cancelTransition()
clearErrors()
canActivate(routeName, true | false)
canDeactivate(routeName, true | false)
routeNodeSelector
- เอาไว้ทำงานกับ
connect
- ทุกครั้งที่มี route change จะมีแค่ node เดียวเท่านั้นที่ต้อง render ใหม่
- node ที่ว่าคือ node ที่สูงที่สุดใน change tree
- logic ที่ต้องเขียนคือวิธีเลือกว่าจังหวะไหนต้องเลือก node ไหนให้ render
router5-helpers
จะมีตัวช่วยสำหรับเขียน logic ที่ว่า
ตัวอย่างโค้ดการเลือก
import { connect } from 'react-redux';
import { routeNodeSelector } from 'redux-router5';
import { Home, About, Contact, Admin, NotFound } from './components';
import { startsWithSegment } from 'router5-helpers';
function Root({ route }) {
const { params, name } = route;
const testRoute = startsWithSegment(name);
if (testRoute('home')) {
return <Home params={ params } />;
} else if (testRoute('about')) {
return <About params={ params } />;
} else if (testRoute('contact')) {
return <Contact params={ params } />;
} else if (testRoute('admin')) {
return <Admin params={ params } />;
} else {
return <NotFound />;
}
}
export default connect(state => routeNodeSelector(''))(Root);
จากโค้ดจะเห็นว่าตัว routerNodeSelector
จะส่ง route ลงมาให้ Component ข้างล่างมัน เพื่อใช้ตัดสินใจว่าควรจะเลือก render ตัวไหน