Redux简介

Redux

Redux 是 JavaScript 状态容器,提供可预测化的状态管理。

Redux官网:https://redux.js.org/

Redux中文文档:https://cn.redux.js.org/

react-redux官网:https://react-redux.js.org/

Redux视频:https://egghead.io/courses/getting-started-with-redux

Provide

全局引入react-redux

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import React from 'react'
import ReactDOM from 'react-dom'

import { Provider } from 'react-redux'
import store from './store'

import App from './App'

const rootElement = document.getElementById('root')
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
)

connect

组件中使用react-redux

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { connect } from 'react-redux'
import { increment, decrement, reset } from './actionCreators'

// const Counter = ...

const mapStateToProps = (state /*, ownProps*/) => {
return {
counter: state.counter
}
}

const mapDispatchToProps = { increment, decrement, reset }

export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter)

redux-thunk

redux-thunk就是redux的中间件,中间件就是你可以在收到请求和返回请求之间做一些操作。

github地址:https://github.com/reduxjs/redux-thunk

用法,在store.js文件中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunkMiddleware from 'redux-thunk';
import reducer from './reducers';

const initializeStore = (initialState = {}) => createStore(
reducer,
initialState,
process.env.NODE_ENV === 'production'
? applyMiddleware(thunkMiddleware)
: composeWithDevTools(applyMiddleware(thunkMiddleware)),
);

export default initializeStore;

redux-thunk最重要的思想,就是可以接受一个返回函数的action creator。如果这个action creator 返回的是一个函数,就执行它,如果不是,就按照原来的next(action)执行。

1
2
3
4
5
6
7
8
9
10
11
export function addCount() {
return {type: ADD_COUNT}
}

export function addCountAsync() {
return dispatch => {
setTimeout( () => {
dispatch(addCount())
},2000)
}
}

Hooks

useSelector

基本用法:

1
2
3
4
5
6
7
import React from 'react'
import { useSelector } from 'react-redux'

export const CounterComponent = () => {
const counter = useSelector(state => state.counter)
return <div>{counter}</div>
}

useDispatch

基本用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import React from 'react'
import { useDispatch } from 'react-redux'

export const CounterComponent = ({ value }) => {
const dispatch = useDispatch()

return (
<div>
<span>{value}</span>
<button onClick={() => dispatch({ type: 'increment-counter' })}>
Increment counter
</button>
</div>
)
}