八十六、推荐组件的redux-thunk异步解决方案、Ajax获取推荐数据
| 2020/11/22、 周日、今天又是奮斗的一天。 |
@Author:Runsen
今天我們來看一個 Redux 官方出品的 middleware 庫:redux-thunk。
Redux官方實現的異步解決方案----Redux-Thunk
Redux-Thunk和前面寫過的Redux和React-Redux其實都是Redux官方團隊的作品,他們的側重點各有不同:
Redux:是核心庫,功能簡單,只是一個單純的狀態機,但是蘊含的思想不簡單,是傳說中的“百行代碼,千行文檔”。
React-Redux:是跟React的連接庫,當Redux狀態更新的時候通知React更新組件。
Redux-Thunk:提供Redux的異步解決方案,彌補Redux功能的不足。
比如,當我聚焦的時候,推薦組件需要出現,搜索框需要拉長。這里涉及了兩種函數,需要使用redux-thunk異步。
安裝redux-thunk:cnpm install redux-thunk
import {createStore,compose, applyMiddleware} from 'redux' import thunk from 'redux-thunk' import reducer from './reducer' // reduxredux中的高級用法 引入redux-thunk 異步 const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore(reducer,composeEnhancers(applyMiddleware(thunk) )) export default store;index.js代碼如下。
import React ,{Component} from 'react' import { CSSTransition } from 'react-transition-group' import { connect } from 'react-redux' import {actionCreators} from './store' import {HeaderWrapper,Logo,Nav,NavItem,NavSearch,SearchWrapper,Addition,Button,SearchInfo,SearchInfoTitle,SearchInfoSwitch,SearchInfoItem,SearchInfoList, } from './style'class Header extends Component{getListArea() {const {focused, list} = this.propsif (focused) {return (<SearchInfo><SearchInfoTitle>熱門搜索<SearchInfoSwitch>換一批</SearchInfoSwitch></SearchInfoTitle><SearchInfoList>{list.map((item) => {return <SearchInfoItem key={item}> {item} </SearchInfoItem>})}</SearchInfoList></SearchInfo>)}else{return null}}render() {const {focused, handleInputFocus,handleInputBlur} = this.propsreturn (<HeaderWrapper><Logo></Logo><Nav><NavItem className='left active'>首頁</NavItem><NavItem className='left'>下載App</NavItem><NavItem className='right'>登錄</NavItem><NavItem className='right'><i className="iconfont"></i></NavItem><SearchWrapper><CSSTransitionin={focused}timeout={200}classNames="slide"><NavSearchclassName={focused ? 'focused' : ''}onFocus={handleInputFocus}onBlur={handleInputBlur}></NavSearch></CSSTransition>{/* vscode快捷鍵Ctrl + Shift + L */}<i className={focused ? 'focused iconfont' : 'iconfont'}></i>{this.getListArea()}</SearchWrapper></Nav><Addition><Button className='writting'><i className="iconfont"></i> 寫文章</Button><Button className='reg'>注冊</Button></Addition></HeaderWrapper>)} }const mapStateToProps = (state) => {return {// state.getIn是immutable fromJS的用法 相當于 // state.get('header').get('focused')focused: state.getIn(['header','focused']),list: state.getIn(['header','list'])} }const mapDispathToProps = (dispatch) => {return {handleInputFocus() {dispatch(actionCreators.getList());dispatch(actionCreators.searchFocus());},handleInputBlur() {dispatch(actionCreators.searchBlur());}} }export default connect(mapStateToProps, mapDispathToProps)(Header);Ajax獲取推薦數據
在actionCreators中有一個getList,來獲取推薦數據。我們需要使用Ajax獲取推薦數據。
React 只是使用 props 和 state 兩處的數據進行組件渲染。
個人推薦 axios,這也是本文所使用的。不過,認真的說,如果你偏偏不喜歡它,那就選其他的唄,比如Promise。
安裝:cnpm install axios --save
import * as constants from './constants' import axios from 'axios' import {fromJS} from 'immutable'export const searchFocus = () =>({type: constants.SERACH_FOCUS })export const searchBlur = () =>({type: constants.SERACH_BLUR })const changList = (data) => ({type: constants.CHANGR_LIST,// fromJS處理data: fromJS(data) })export const getList = () =>{return (dispatch) => {axios.get('/api/headerList.json').then((res) => {const data = res.datadispatch(changList(data.data))}).catch(()=>{console.log('error')})} } import * as constants from './constants' import {fromJS} from 'immutable'const defaultState = fromJS({focused: false,list: [] });// eslint-disable-next-line import/no-anonymous-default-export export default (state = defaultState, action) => {// eslint-disable-next-line default-caseswitch(action.type) {case constants.SERACH_FOCUS : return state.set('focused',true);case constants.SERACH_BLUR : return state.set('focused',false);case constants.CHANGR_LIST : return state.set('list',action.data)}return state; }總結
以上是生活随笔為你收集整理的八十六、推荐组件的redux-thunk异步解决方案、Ajax获取推荐数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基金当天赎回算哪一天的
- 下一篇: 微贷网上征信吗