创建react文件及使用redux原创

原创
小哥 5个月前 (02-08) 阅读数 57 #大杂烩

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:value1})   // 1强数型的含义

(4)倾听变化  再index.js文件中

import store from ./redux/store

把它包起来,只要app监控何时发生更改 ,不要害怕,想想react的diff属性,则只更新更改的部分。

store.subscribe(() =>
    ReactDOM.render(
        
            
        ,
        document.getElementById(root)
    )
)

总结:

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除