React-redux
底层:通过高阶组件 + context跨组件传值实现,用
<Provider>
包裹根元素, 解决了在组件中频繁引用store。
- 安装
cnpm install redux -S
- reducers/num.js仍然按照常规的方式写
const defaultState = {
n: 10
}
export default (state = defaultState, action) => {
switch (action.type) {
case "NUM_ADD":
let numState = Object.assign({}, state);
numState.n++;
return numState;
}
return state;
}
- reducers/index.js,引入createStore和combineReducers
通过combineReducers合并多个reducers
import { createStore, combineReducers } from "redux"
import num from "./reducers/num"
import todo from "./reducers/todo"
const reducers = combineReducers({
num,
todo
})
const store = createStore(reducers);
export default store;
- src/index.js
在index.js中引入provider包裹根元素,只需在这里引入一次store,App的所有子组件就默认都可以拿到state了。
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
import { Provider } from "react-redux"
import store from "./store"
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById("root"));
- App.js
在使用的组件中,引入connect,它是由两个函数组成:第一个函数必须返回对象,在第二个函数填入组件。使得UI层和逻辑层自动做了分隔。
import React, { Component } from 'react'
import { connect } from "react-redux"
class App extends Component {
render() {
return (
<div>
<h2>{this.props.n}</h2>
<button onClick={this.props.handleAdd.bind(this)}>点击</button>
</div>
)
}
}
//将state中的数据通过映射的方式,映射到props上
const mapStateToProps = (state) => ({
n: state.num.n
})
//将dispatch中的数据通过映射的方式,映射到props上
const mapDispatchToProps = (dispatch) => ({
handleAdd() {
var action = {
type: "NUM_ADD"
}
dispatch(action)
}
})
export default connect(mapStateToProps, mapDispatchToProps)(App);
网友评论