脚本宝典收集整理的这篇文章主要介绍了React手稿之 React-Redux,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
React-redux
Redux
-
Action
function addTodo(text) {
return {
tyPE: ADD_TODO,
text
}
}
type
属性是必须的。
-
Reducer
function todoApp(state = inITialState, action) {
switch (action.type) {
case ADD_TODO:
return Object.assign({}, state, {
todo: action.todo
})
default:
return state
}
}
1、需要一个case
与action
的type
一致。
2、必须在switch
的defautl
返回原state
。
-
React-Redux
是Redux的React实现,可参考 Official React bindings for Redux.
安装
yarn add redux react-redux
//or
npm i redux react-redxu
组件层级划分
-
表现性组件
只负责显示UI的组件。
例如:
<div></div>
-
容器性组件
不处理UI的组件,也不处理数据,只为UI组件提供数据的组件。
例如:
connect(state => state)(<Yourcomponent />)
- 其他组件
除以上两种组件以外的组件。
使用Redux
我们以一个计数器的例子来说明如何使用React-redux.
-
设计表现性组件
需要:显示当前计数,默认为0;累加按钮,每次单击加1;递减按钮,每次单击减1;重置按钮,单击将计数设置为0。
import React From 'react';
export default ({counter = 0}) => {
const styles = {
display: 'flex',
justifyContent: 'space-around'
};
return (
<div>
<h1>当前计数为:{counter}</h1>
<div style={styles}>
<button>加</button> <button>减</button> <button>重置</button>
</div>
</div>
);
};
-
设置容器性组件
目的是将表现性组件中的数据抽离出去交给redux管理,然后通过容器性组件将redxu与表现性组件关联起来。
import { connect } from 'react-redux';
import CounterIndex from '../components/chapter03/Counter';
export default
connect(state => ({ ...state.counterRedux }))(({ counter, dispatch }) => <CounterIndex counter={counter} dispatch={dispatch} />);
-
Action
export const COUNTER_ACTION = 'COUNTER_ACTION';
export const addActioner = ({counter}) => {
return {type: COUNTER_ACTION, counter: counter + 1};
};
export const subActioner = ({counter}) => {
return {type: COUNTER_ACTION, counter: counter - 1};
};
export const resetActioner = () => {
return {type: COUNTER_ACTION, counter: 0};
};
-
Reducer
import { COUNTER_ACTION } from '../actions/CounterAction';
export default (state, action) => {
switch (action.type) {
case COUNTER_ACTION:
return { ...state, counter: action.counter };
default:
return state;
}
}
-
Store
import React from 'react';
import { PRovider } from 'react-redux';
import { createstore } from 'redux';
import CounterReducer from '../reducers/CounterReducer';
let store = createStore(CounterReducer);
export default ({ children }) => <Provider store={store}>{children}</Provider>
Redux 调试插件
-
console日志
安装redux-LOGger组件:yarn add redux-logger --dev
。
然后加入到redux store中即可:
import { createLogger } from 'redux-logger';
store = createStore(reducers, createLogger());
例如:
-
redux扩展程序
需要在Chrome应用市场安装Redux DevTools.
然后在store中使用增强功能将redux-logger加入即可:
const logger = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__(createLogger());
store = createStore(reducers, logger);
推荐阅读《React 手稿》
以上是脚本宝典为你收集整理的React手稿之 React-Redux全部内容,希望文章能够帮你解决React手稿之 React-Redux所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。