1.创建react
npm install create-react-app
create-create-app 项名名称
2.使用redux
2.1安装 yarn add redux
2.2创建一个与compontents 同级的文件夹redux 创建两个js文件 一个store.js 一个count_reducer.js
store.js代码如下
/**
* 该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/
// 引入createStore方法,专门用户创建redux中最为核心的store对象
import {createStore} from 'redux'
// 引入为count组件服务的reducer
import countReducer from './count_reducer'
// 暴露store
export default createStore(countReducer)
count_reducer.js 代码如下
/**
* 1.该文件用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数
* 2.reducer函数会接到两个参数,分别为:之前的状态(prestate)。动作对象(action)
* 3.下文preState=initState的意思就是如果给你传了prestate参数,如果没传初始化那种就默认去initState的值
*/
const initState = 0
export default function countReducer (preState=initState, action) {
const {type, data} = action
// 根据type决定如何加工数据
switch (type) {
case 'increment':
return preState + data
case 'decrement':
return preState - data
default:
return preState
}
}
2.3redux 使用啦
(1)在要使用的地方引入 import store from '../../redux/store'
(2)获取store传过来的值 store.getState()
(3)通知redux要分发对象 store.dispatch({type:'increment',data:value*1}) // *1的意思是强转数字类型
(4)监听发生变化 再index.js文件中
import store from './redux/store'
包裹起来,只要app发生变化就监听 ,不要怕,以为react的diff属性,只会更新发生变化的部分
store.subscribe(() =>
ReactDOM.render(
<React.StrictMode>
<App/>
</React.StrictMode>,
document.getElementById('root')
)
)
总结: