安装
yarn add redux --save
yarn add react-redux --save
redux 调试工具
首先 在chrome中 安装 Redux Devtools 扩展
yarn add redux-devtools-extension
-----------------------react redux demo -------------------------------开始------------------------------------------------------------
1、 创建 redux 文件夹
redux
action
index.js
reducer
index.js
store
configureStore.js
action、index.js 内容
export const type = {
SWITCH_MENU: 'SWITCH_MENU'
}
export function switchMenu (menuName) {
return {
type: type.SWITCH_MENU,
menuName
}
}
reducer、index.js 内容
// Reducer 数据处理
import { type } from './../action'
const initialState = {
menuName: '首页'
}
export default (state = initialState, action) => {
switch (action) {
case type.SWITCH_MENU:
return {
...state,
menuName: action.menuName
}
default:
return {
...state
}
}
}
store、configureStore.js 内容
// 引入 crateStore 创建store
import { createStore } from 'redux'
import reducer from './../reducer'
// import {composeWithDevTools} from 'redux-devtools-extension'
export default () => createStore(reducer)
// export default () => createStore(reducer,composeWithDevTools())
// 在最外层 index.js 中
一、获取 redux 里的值
import { connect } from 'react-redux'
// 获取数据源
const mapStateToProps = state => {
return {
menuName: state.menuName
}
}
export default connect(mapStateToProps)(Home) //Home 为组件 class 的名字
// 页面中取值{this.props.menuName}
二、 改变redux 内部得状态
import { connect } from 'react-redux'
import { switchMenu } from './../redux/action'
方法中使用
onChange = (a, b, c) => {
const { dispatch } = this.props
dispatch(switchMenu('迪迦'))
}
export default connect()(Home) //Home 为组件 class 的名字
-----------------------react redux demo -------------------------------------结束------------------------------------------------------
redux
Redux = Reducer + Flux
新建store文件夹 另一种 方法 demo
store
index.js
reducer.js
reducer.js 内容
const defaultState = {
inputValue:'迪迦奥特曼',
list: []
}
// reducer 可以接受 state 但是绝不能修改state
export default (state = defaultState ,action) = >{
if(action.type==='change_input_value'){
const newState = JSON.parse(JSON.stringify(state)); 、、 先拷贝一份
newState.inputValue = action.value
return newState
}
return state;
}
index.js 内容 创建store
import { createStore} from 'redux'
import reducer from './reducer'
consot store = createStore(reducer )
export default store
组件中使用
import store from './store'
class TodoList extends react.component{
constructor(props){
super(props);
console.log(store.getState()) // 此时的 内容 就是 defaultState 里的内容
store.subscribe(this.handleStoreChange) 当store 发送变化执行这个
}
handleStoreChange(){
this.setState(store.getState()) // 重新去 store 的值
}
changeRedux = ()=>{
const action = {
type: 'change_input_value',
value: '大师兄'
}
store.dispatch(action)
}
}