您的位置:首页 > Web前端 > React

React生态——Redux(1)

2018-03-30 00:07 489 查看

Redux

是什么

Redux专注于状态管理,与react解耦,不是强结合(它也可以用于别的框架);

单一状态,单向数据流;

核心概念:store,state,action,reducer

通俗解释

少的时候,无论更改什么,都用setState();

多了以后,管理不过来;

所有的state交给redux管理,组件只负责view。

功能

store记录所有的state;

需要改变的时候,由dispatch触发action;

reducer拿到旧的state以及action,生成新state;

使用步骤

定义Reducer接受state和action,返回新的state;

通过reducer新建store,使用store.getState获取状态;

需要store.dispatch(action)来修改state;

store.subscribe监听每次修改

例子

// 引入createStore
import {createStore} from 'redux';

// 1.定义reducer(即计算规则)
function counter(state=0, action){
// action有多种type
switch(action.type){
case '+原味甜筒':
return state + 1;

case '-原味甜筒':
return state - 1;

default:
return 10;
}
}

// 2.新建store
const store = createStore(counter);

// 3.获取state
const init = store.getState();

// 4.监听变化
function listener(){
const current = store.getState();
console.log(`现在有甜筒${current}`);
}
store.subscribe(listener);

// 5.修改state
store.dispatch({type:'+原味甜筒'});
store.dispatch({type:'+原味甜筒'});
store.dispatch({type:'+原味甜筒'});


react和redux一起使用

简单例子

1. 创建index.redux.js

定义action.type常量

定义reducer

创建action方法,返回action.type

具体代码如下:

// 1.定义action.type
const ADD_ICE = '+原味甜筒';
const REDUCE_ICE = '-原味甜筒';

// 2.定义reducer(即计算规则)
export function counter(state=0, action){

// action有多种type
switch(action.type){

case ADD_ICE:
return state+1;

case REDUCE_ICE:
return state-1;

default:
return 10;
}
}

// 3.创建action
export function addIce(){
return {type:ADD_ICE}
}

export function reduceIce(){
return {type:REDUCE_ICE}
}


2. 创建index.js

引入上面定义的reducer,创建store

渲染App组件,传入参数store、addICE

使用render方法,真正渲染App组件

store.subscribe()监听render方法

注:监听里面发生的事件,一旦dispatch(),重新渲染。

具体代码如下:

import React f
4000
rom 'react';
import ReactDom from 'react-dom';
import {createStore} from 'redux';

import App from './App';
import {counter,addIce,reduceIce} from './index.redux';

// 1.创建store
const store = createStore(counter);

// 2.渲染App组件到root标签上
function render(){
ReactDom.render(
<App store={store} addIce={addIce} reduceIce={reduceIce}/>,
document.getElementById('root')
);
}

// 3.使用render方法
render();

// 4.监听render方法
store.subscribe(render);


3. 创建App.js

this.props.store获取传入的store,addICE同理

获取现在的state

用dispatch()触发action方法,更新state

具体代码如下:

import React from 'react';

class App extends React.Component
{

render(){
// 获取传入组件的store
const store = this.props.store;

// 获取传入组件的store
const addIce = this.props.addIce;

// 获取传入组件的store
const reduceIce = this.props.reduceIce;

// 获取现在的state
const num = store.getState();

return (
<div>
<h1>现在有原味甜筒{num}</h1>
<button onClick={()=>store.dispatch(addIce())}>增加甜筒</button>
<button onClick={()=>store.dispatch(reduceIce())}>减少甜筒</button>
</div>

)
}
}

export default App;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: