本文结合小例子讲解redux的用法,适合有一定redux基础的,了解redux各个模块但是不太会运用的同学来了解哦,没有基础的建议先看redux基础再来哦~(附上redux官网链接https://www.redux.org.cn/
)
下面进入正题,首先附上代码结构
第一步,构建store.js,直接上代码:
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import reducer from './reducers'
const store = createStore(reducer, applyMiddleware(thunk))
export default store
这里通过createStore创建store,传入reducer和异步中间件。
第二步,构建App.js,上代码:
import React, { Component } from 'react';
import './App.css';
import { HashRouter as Router, Route, Redirect, Switch } from 'react-router-dom'
import store from './store'
import { Provider } from 'react-redux'
import Home from './pages/Home'
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<Switch>
<Redirect from='/' to='/home' exact />
<Route path='/home' component={Home} />
</Switch>
</Router>
</Provider>
)
}
}
export default App;
这里我们在App.js里面需要通过Provider注入store,并且我结合了hash路由进行一个路由的匹配,不了解路由的自行学习哦~。
第三步,构建一个异步请求的工具utils/http.js,上代码:
import axios from 'axios'
const http = {
get({ url = "", params = {} } = {}) {
return axios({
url: url,
method: 'GET',
params
})
.then(result => result.data)
.catch(err => {
throw new Error(err)
})
},
post({ url = "", params = {}, data = {}, headers = {} } = {}) {
return axios({
url: url,
method: 'POST',
params,
data,
headers
})
.then(result => result.data)
.catch(err => {
throw new Error(err)
})
}
}
export default http
这里我用的axios进行异步请求,配置了get和post两种方式。
第四步,构建发起请求的services/countService.js,上代码:
import http from '../utils/http'
/**
* 获取数量
*/
export const fetchCountService = async () => {
let result = await http.get({
url: 'https://api.myjson.com/bins/1a48uq'
}).catch(err => {
throw new Error(err);
}
)
if (result.data) {
return result.data
} else {
throw new Error('缺少data字段')
}
}
这里我用的请求地址是Myjson这个网站,可以自行构建数据生成请求地址(附上链接:http://myjson.com/
),下面是我简单构建的数据:
第五步,构建action,在actions文件夹下,我创建了一个index.js文件和count.js文件。
index.js文件用于引入所有的action,便于在组件中直接导入actions即可,代码如下:
export * from './count'
接下来构建count.js文件,将异步请求获取到的数据派发给reducer,上代码:
import {
fetchCountService
} from '../services/countService'
/**
* 查询数量
*/
export const FETCH_COUNT_REQUEST = 'FETCH_COUNT_REQUEST'
export const FETCH_COUNT_SUCCESS = 'FETCH_COUNT_SUCCESS'
export const FETCH_COUNT_FAILURE = 'FETCH_COUNT_FAILURE'
export const fetchCount = () => async (dispatch, getState) => {
dispatch({
type: FETCH_COUNT_REQUEST
})
let res = await fetchCountService().catch(err => {
dispatch({
type: FETCH_COUNT_FAILURE
})
throw new Error(err)
})
dispatch({
type: FETCH_COUNT_SUCCESS,
payload: res
})
return res
}
第六步,构建reducer,在reducers文件夹下,我创建了一个index.js文件和count.js文件。
index.js文件用于引入所有的reducer,便于在App.js组件中直接导入reducers即可,代码如下:
import { combineReducers } from 'redux'
import count from './count'
const reducer = combineReducers({
count
})
export default reducer
这里用到了combineReducers将所有到reducer结合到一起。
接下来构建count.js文件,将数据存储到redux,上代码:
import {
FETCH_COUNT_REQUEST,
FETCH_COUNT_SUCCESS,
FETCH_COUNT_FAILURE
} from '../actions'
const defaultState = {
fetchStatus: '',
count: null
}
const count = (state = defaultState, action) => {
const { type, payload } = action
switch (type) {
case FETCH_COUNT_REQUEST:
return {
...state,
fetchStatus: 'LOADING',
count: null
}
case FETCH_COUNT_SUCCESS:
return {
...state,
fetchStatus: 'SUCCESS',
count: payload
}
case FETCH_COUNT_FAILURE:
return {
...state,
fetchStatus: 'FAILURE',
count: null
}
default:
return state
}
}
export default count
最后一步,在Home组件中使用即可,构建Home/index.js文件,上代码:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { fetchCount } from '../../actions'
class Home extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
this.props.fetchCount().then(res => {
console.log('成功了', res)
}).catch(err => {
console.log('出错了', err)
})
}
render() {
const { count, fetchStatus } = this.props
let content = null
if (fetchStatus === 'LOADING') {
content = <p>加载中</p>
} else if (fetchStatus === 'SUCCESS') {
content = <p>数量:{count.count}</p>
} else {
content = <p>出错了</p>
}
return (
<div>
首页
{content}
</div>
)
}
}
const mapStateToProps = ({ count }) => {
return {
...count
}
}
const mapDispatchToProps = {
fetchCount
}
export default connect(mapStateToProps, mapDispatchToProps)(Home)
这里通过react-redux里的connect传入mapStateToProps和mapDispatchToProps,这样就可以在组件中调用action啦,发起异步请求获取数据并存入redux。
以上就是完整的栗子啦,希望能帮到各位小伙伴,有什么问题欢迎指出哦,共同进步啦~