一、安装
npm install -g create-react-app
二、创建react应用
create-react-app 项目名称
进入项目文件
npm start 或 yarn
npm run eject 暴露webpack
安装包配置自己可以重新分配一下,其实并不影响打包,打包模块插件是按引入打包,不引入的不会打包的
添加redux
yarn add redux
src下创建两个文件store下的index和reducer
//store/index.js
import {createStore} from 'redux';
import reducer from './reducer';
const store =createStore(reducer);
export default store;
//store/reducer.js
const defaultState={
texts:'',
list:[1,2]
};
export default (state=defaultState,action)=>{
return state;
}
添加antd,并且按需引入
yarn add antd
yarn add babel-plugin-import
然后在package.json中加入
"plugins": [
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style": "css"
}
]
]
Redux store 仅支持同步数据流。使用 thunk
等中间件可以帮助在 Redux 应用中实现异步性。可以将 thunk
看做 store 的 dispatch()
方法的封装器;我们可以使用 thunk
action creator 派遣函数或 Promise,而不是返回 action 对象。
注意,没有 thunk
的话,默认地是同步派遣。也就是说,我们依然可以从 React 组件发出 API 调用(例如使用 componentDidMount()
生命周期方法发出这些请求),但是我们在 Redux 应用中难以实现以下两点:
- 可重用性(思考下合成)
- 可预测性,只有 action creator 可以是状态更新的单一数据源
要在应用中使用 thunk
中间件,请务必安装 redux-thunk 软件包:
yarn add redux-thunk
store/index.js
import {createStore,compose, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store=createStore(reducer, composeEnhancers(
applyMiddleware(thunk)
));
export default store;
安装
yarn add redux-immutable
或
npm install --save redux-immutable
src\store\reducer.js
import {combineReducers} from 'redux-immutable'
// import { type } from '../action';
import {reducer as menuReducer} from '../components/NavLeft/store';
import {reducer as userReducer} from '../pages/user/store';
const reducer= combineReducers({
menu:menuReducer,
user:userReducer,
});
export default reducer;
如果报错
是因为 redux-immutable 依赖 使用 Immutable
yarn add immutable
理解参考以下博客
https://blog.csdn.net/m0_37527015/article/details/84338831
https://www.jianshu.com/p/3e162080711b
https://www.cnblogs.com/greatluoluo/p/8469224.html
使用 Immutable 后,如下图,当红色节点的 state 变化后,不会再渲染树中的所有节点,而是只渲染图中绿色的部分:
安装
yarn add react-redux
项目的index.js,整个项目的唯一第一入口
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App'
// import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);