Redux创建过程

yarn add redux react-redux redux-devtools

redux-devtools(是调试redux的)

首先需要创建文件夹 store

store创建一个index.js

4B8BF8E4A6524AAF8D43C78BBE6FFAECuploading.4e448015.gif转存失败重新上传取消

store文件index.js 内容

import { createStore } from "redux"; export default function configureStore() { const store = createStore(); return store; }

 

什么时候需要用到redux 只有在关联的时候 才会用到react-redux

 

然后 再去创建reducers文件夹

E2027C0135E14472A210B97EB73CC5FEuploading.4e448015.gif转存失败重新上传取消

reducers文件auth.js 内容

const initState = {}; export default function auth(state = initState, action) { switch (action.type) { case "INIT_AUTH": return (state = action.data); case "UPDATE_AUTH": return (state = action.data); default: return state; } }

 

reducers文件index.js 内容

import { combineReducers } from "redux"; import auth from "./auth"; const rootReducers = combineReducers({ auth }); export default rootReducers;

然后再去创建actions文件夹

744937649E81423689B7D60E53DB7C46uploading.4e448015.gif转存失败重新上传取消

action文件auth.js 内容

export function initAuth(data) { return { type: "INIT_AUTH", data }; } export function updateAuth(data) { return { type: "UPDATE_AUTH", data }; }

 

然后去store/index.js中去使用 新增代码

import { createStore } from "redux"; import rootReducers from "../reducers/index"; export default function configureStore() { const store = createStore( rootReducers, window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__() : undefined ); return store; }

 

接下来了 就该去关联了 主入口文件index.js进行关联

import { Provider } from "react-redux"; import configtureStore from './store' const store = configtureStore(); Provider这个标签 要放在最外面进行包裹 <Provider store={store}> <App/> </Provider>

然后 你在哪个页面需要这个数据 再到这个页面进行关联

 

下面的方案是可以读取可以修改

import {connect} from 'react-redux' import * as authAction from '../actions/auth' import {bindActionCreators} from 'redux //这是读取 function mapStateToProps (state) { return { auth:state.auth } } //这是设置 function mapDisptachToProps (dispatch) { return { authActions: bindActionCreators(authAction, dispatch) }; }; export default connect(mapStateToProps,mapDisptachToProps)(App)

 

componentDidMount() { this.props.authActions.initAuth({ name:'测试' }) }

 

下面的方案是 只读取

import {connect} from 'react-redux' //这是读取 function mapStateToProps (state) { return { auth:state.auth } } export default connect(mapStateToProps)(App)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值