diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index b8f86643..d4bd0bca 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -69,10 +69,13 @@ export default defineConfig({ copyright: 'Copyright © 2019-present Ziu Chen' }, lastUpdatedText: 'Updated Date', - algolia: { - apiKey: 'b4fd296ea5e467b3ac4a582160ff3122', - indexName: 'ziuchenio', - appId: 'LFZ2CPWWUG' + search: { + provider: 'algolia', + options: { + appId: 'LFZ2CPWWUG', + apiKey: 'b4fd296ea5e467b3ac4a582160ff3122', + indexName: 'ziuchenio' + } } } }) diff --git a/docs/note/React.assets/redux-async-action.svg b/docs/note/React.assets/redux-async-action.svg new file mode 100644 index 00000000..bd6f4736 --- /dev/null +++ b/docs/note/React.assets/redux-async-action.svg @@ -0,0 +1,16 @@ + \ No newline at end of file diff --git a/docs/note/React.assets/redux-usage.svg b/docs/note/React.assets/redux-usage.svg new file mode 100644 index 00000000..4c584d75 --- /dev/null +++ b/docs/note/React.assets/redux-usage.svg @@ -0,0 +1,16 @@ + \ No newline at end of file diff --git a/docs/note/React.md b/docs/note/React.md index 59a569b3..5b75bbc5 100644 --- a/docs/note/React.md +++ b/docs/note/React.md @@ -3874,6 +3874,8 @@ export default store ``` ::: + + ### 进一步封装 可以将耦合在一起的代码拆分到不同文件中 @@ -4110,4 +4112,167 @@ export default connect( - 为高阶组件传入映射目标组件,最后高阶组件返回一个新组件 - 新组件的props包含了来自Store中状态/dispatch的映射 +### 异步Action + +有些场景下,我们希望组件能够直接调用Store中的action来触发网络请求,并且获取到数据 + +但是dispatch只允许派发对象类型的Action,不能通过dispatch派发函数 + +可以通过中间件`redux-thunk`来对Redux做增强,让dispatch能够对函数进行派发 + +```bash +npm i redux-thunk +``` + +通过`applyMiddleware`引入`redux-thunk`这个中间件: + +::: code-group +```tsx [index.js] {2,3,6} +// store/index.js +import { createStore, applyMiddleware } from 'redux' +import thunk from 'redux-thunk' +import reducer from './reducer' + +const store = createStore(reducer, applyMiddleware(thunk)) + +export default store +``` +```tsx [actionFactory.js] +// actionFactory.js +export const fetchPostList = () => { + return (dispatch, getState) => { + fetch('https://jsonplaceholder.typicode.com/posts') + .then((res) => res.json()) + .then((res) => { + dispatch({ + type: actionType.FETCH_POST_LIST, + list: res + }) + }) + } +} +``` +```tsx [list.jsx] +// list.jsx +import React, { Component } from 'react' +import { connect } from 'react-redux' +import { fetchPostList } from './store/actionFactory' + +const mapStateToProps = (state) => ({ + list: state.list +}) + +const mapDispatchToProps = (dispatch) => ({ + fetchList: () => dispatch(fetchPostList()) +}) + +export default connect( + mapStateToProps, + mapDispatchToProps +)( + class Profile extends Component { + render() { + return ( +