方法一、只使用redux对项目进行管理
view
在视图层通过store的dispatch接受action的store.
getStore()来接受reduce中的store值。并通过Store.subscribe进行监听,changeitem实时的改变state中的getSrore值。
action
let Action ={
addItem(msg){
return{
type:'ADD',
text:msg
}
}
}
export default Action;
action中是定义数据的类型的
store
import {createStore} from "redux"
import Reducer from "./Reducer"
let Store=createStore(Reducer)
export default Store;
创建一个store仓库(状态管理器)
reducer
import {combineReducers} from "redux"
import Address from "./Address"
let Reducer=combineReducers({
Address:Address
})
export default Reducer;
运用拆分(combineReducers)发,可以定义多个state类型,这样也有利于对数据的管理。
方法二、使用redux + react-redux
1.安装第三方库
npm i redux react-redux --save
2.页面构建
- 新建ComC文件夹下边有index.js和children.js,在App.js中引入组件
- 创建redux文件夹下方包括store.js、action.js、reducer.js
- 创reducer.js文件下运用拆分combineReducers,同时将action引入,这样可以创建多个库
import { combineReducers } from 'redux';
import { sendResult, sendBool } from './action';
const reducer = combineReducers({
sendResult,
sendBool,
})
export default reducer;
- store.js文件下(创建store库,导入我们自己写好的reducer.js文件)
import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(reducer);
export default store;
- action文件下(主要处理事件)
const init = [
{ name: '1', key: '1' }
]
const sendResult = (state = init, action) => {
switch (action.type) {
case 'add_result':
let arr = [...state];
arr.push(action.msg);
state = arr;
return state;
default:
return state
}
}
const sendBool = (state = { bool: false }, action) => {
switch (action.type) {
case 'boolFalse':
return {
bool: false
}
case 'boolTrue':
return {
bool: true
}
default:
return state
}
}
module.exports = {
sendResult,
sendBool,
}
3.provider(用于包裹整个结构,使整个app都可以获取到store中的数据)
1.使用provider将项目进行包裹,同时传值store
import { Provider } from 'react-redux';
import store from './redux/store';
export default class App extends Component {
render () {
return (
<Provider store={store}>
<Router>
<Switch>
<Route path="/home" component={ComC}></Route>
<Redirect to="/home" />
</Switch>
</Router>
</Provider>
)
}
}
4.connect(如果我们需要接受provider提供的store,就需要把我们组件使用connect加强,使组件跟store进行关联)
connect参数
5.connect语法
- connect(要接受数组的函数,要发送action的函数)(放入要加强对组件)
- 如果只需要接受store或发送action,将另一个函数输入为null就可以了
import { connect } from 'react-redux';
const mapDispatchToProps = (dispatch) => {
return {
sendResult: (msg) => {
dispatch({ type: 'add_result', msg })
},
sendBool: (msg) => {
dispatch(msg)
}
}
}
export default connect(null, mapDispatchToProps)(ComC);
- 可以在this.props中打印出sendResult函数 (可以在reducer中打印state,进行验证是否发送action)
6.使用connect接收state数据(
import { connect } from 'react-redux';
const mapStateToProps = (state) => {
return state;
}
export default connect(mapStateToProps)(Children);
- 可以在render中打印sendResult,进行验证是否发送action;或者在componentWillReceiveProps中打印nextProps也可以