prop-types------展示组件的props类型检测:
1 import PropTypes from 'prop-types' 2 ... 3 Link.propTypes = { 4 active: PropTypes.bool.isRequired, 5 children: PropTypes.node.isRequired, 6 onClick: PropTypes.func.isRequired 7 }
react-dom------组件渲染:
1 import React from 'react' 2 import { render } from 'react-dom' 3 import { Provider } from 'react-redux' 4 5 let store = createStore(todoApp) 6 7 render( 8 <Provider store={store}> 9 <App /> 10 </Provider>, 11 document.getElementById('root') 12 )
react-redux------全局访问store 和 生成容器组件:
1 import { connect } from 'react-redux' 2 ... 3 const FilterLink = connect( 4 mapStateToProps, 5 mapDispatchToProps 6 )(Link)
redux------组装Reducer 和 生成store:
1 // ./reducers 2 import { combineReducers } from 'redux' 3 4 const todoApp = combineReducers({ 5 todos, 6 visibilityFilter 7 }) 8 9 export default todoApp 10 11 // index.js 12 import { createStore } from 'redux' 13 import todoApp from './reducers' 14 15 let store = createStore(todoApp)
redux-thunk 中间件实现异步action:
1 import { createStore, applyMiddleware } from 'redux'; 2 import thunk from 'redux-thunk'; 3 4 let store = createStore( 5 getW, 6 applyMiddleware(thunk) 7 )
异步action实际上是在action creator中生成一个函数,这个函数执行后会生成一个action。我们知道,在redux中action从(dispatch)-(reducer)-(return state)-( store state)的date flow是同步的,但是我们可以调用第三方的中间件(如redux-thunk),在dispacth(action)的时候,由中间件截获action,判断它是不是纯对象。如果是,就直接送到reducer去更新state。如果是函数,就执行它。这个函数我们可以设计为一个异步任务,等异步返回的时候再生成一个纯对象action送到reducer。这就实现了异步操作。
redux-thunk的作用是让dispatch可以接受函数作为参数。如果是函数,就执行它。