REdux需要安装哪些第三方包:
$ yarn add flux
$yarn add react-redux
$yarn add react-router-dom
$yarn add redux-thunk处理异步
middleware 对动作的扩展
reducer
import { combineReducers } from 'redux'
import homeReducer from './homeReducer'
const rootReducer = combineReducers({
homeReducer
})
export default rootReducer
store
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import reducer from './reducer'
const store = createStore(reducer, applyMiddleware(thunk) )
index.js
import { BrowserRouter as Router } from 'react-router-dom'
import { Provider } from 'react-redux'
import store from './store'
ReactDOM.render(
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>
action
import request from 'utils/request'
import { GET_MOVIES, GET_COMMING_MOVIES } from './actionType'
// import axios from 'axios'
export const getMovies = () => {
return async dispatch => {
const result = await request({
url: '/ajax/movieOnInfoList',
params: {
token: ''
}
})
// console.log(result.data)
dispatch({
type: GET_MOVIES,
payload: result.data
})
}
}
export const getCommingMovies = (movieIds) => {
return async dispatch => {
const result = await request({
url: '/ajax/moreComingList',
params: {
token: '',
movieIds,
}
})
// console.log('result', result)
dispatch({
type: GET_COMMING_MOVIES,
payload: result.data
})
}
}
Redux流程
1.store通过reducer创建了初始状态
2.view通过store.getState()获取到了store中保存的state挂载在了自己的状态上
3.用户产生了操作,调用了actions 的方法
4.actions的方法被调用,创建了带有标示性信息的action
5.actions将action通过调用store.dispatch方法发送到了reducer中
6.reducer接收到action并根据标识信息判断之后返回了新的state
7.store的state被reducer更改为新state的时候,store.subscribe方法里的回调函数会执行,此时就可以通知view去重新获取state