Router入门0x205: react-route + redux + react 集成
0x000 概述
这一章终于大集成了
0x001 集成react
源码
import React from 'react' import ReactDom from 'react-dom' class App extends React.Component { render() { return (<div>react</div>) } } ReactDom.render( <App/>, document.getElementById('app') )
- 效果
说明:
- 集成
react
主要是用到react
、react-router
库
- 集成
0X002 集成react-router
源码
import React from 'react' import ReactDom from 'react-dom' import {BrowserRouter, Route, withRouter} from 'react-router-dom' class Article extends React.Component { render() { return ( <p>article</p> ) } } let MyArticle = withRouter(Article) class App extends React.Component { render() { return (<div> <Route component={MyArticle}></Route> </div>) } } let MyApp = withRouter(App) ReactDom.render( <BrowserRouter> <MyApp/> </BrowserRouter>, document.getElementById('app') )
- 效果
说明
- 主要用到
react-router-dom
库,是针对react-router
库在dom
环境下的封装 withRouter
组件,注入match
、location
、history
等属性BrowserRouter
接管跟组件Route
指定路由和组件的对应关系
- 主要用到
0x003 集成redux
源码
引入
redux
相关的包import {Provider, connect} from 'react-redux' import {createStore} from 'redux'
reducer
const counter = (state = {counter: 0, num: 0}, action) => { switch (action.type) { case ACTION_INCREMENT: return {...state, ...{counter: ++state.counter}} case ACTION_DECREMENT: return {...state, ...{counter: --state.counter}} default: return state } }
action
和actionCreators
// action const ACTION_INCREMENT = 'INCREMENT' const ACTION_DECREMENT = 'DECREMENT' // action creator const increment = () => ({ type: ACTION_INCREMENT }) const decrement = () => ({ type: ACTION_DECREMENT })
链接组件
// store const store = createStore(counter) class Article extends React.Component { render() { return ( <p>{this.props.counter}</p> ) } } let MyArticle = withRouter(connect((state) => { return { counter: state.counter } })(Article)) class App extends React.Component { render() { return ( <div> <Route component={MyArticle}></Route> <button onClick={() => this.props.increment()}>+</button> <button onClick={() => this.props.decrement()}>-</button> </div> ) } } let MyApp = withRouter(connect(() => ({}), (dispatch) => { return { increment: () => dispatch(increment()), decrement: () => dispatch(decrement()) } })(App)) ReactDom.render( <Provider store={store}> <BrowserRouter> <MyApp/> </BrowserRouter> </Provider>, document.getElementById('app') )
- 效果
说明
- 主要用到
redux
、react-redux
库 reducer
、action
、actionCreators
都是redux
用的Provider
接管BrowserRouter
,并注入store
connect
连接组件和store
,为组件注入reducer
- 主要用到
0x005 总结
每一步都搞懂,下一步才能更明确。
0x006 资源
相关推荐
opendigg 2020-06-02
weiqi 2020-04-29
mjzhang 2020-04-16
wwzaqw 2020-09-04
游走的豚鼠君 2020-11-10
81417707 2020-10-30
ctg 2020-10-14
小飞侠V 2020-09-25
PncLogon 2020-09-24
jipengx 2020-09-10
颤抖吧腿子 2020-09-04
maple00 2020-09-02
青蓝 2020-08-26
罗忠浩 2020-08-16
liduote 2020-08-13
不知道该写啥QAQ 2020-08-02
pengruiyu 2020-08-01
wmd看海 2020-07-27