react-redux
是用来简化redux使用的
核心API
Provider组件
全局的index.js文件中
import React from "react";
import ReactDOM from "react-dom";
import Todolist from "./Todolist";
import { Provider } from "react-redux";新增语句
import store from "./store";也是新增的,原来只是在<Todolist />组件中
const App = (
<Provider store={ store }> 作用:放置在Provider中的所有组件都可以获取到store的内容
<Todolist />
</Provider>
)
ReactDOM.render(App, document.getElementById("root"));
connect方法:用于包装 UI 组件生成容器组件
原来Todolist 组件中的constructor可以删掉了,import connect from "react-redux";
改造后的样子如下
import React, { Component } from "react";
import store from "./store/index.js";
import { connect } from "react-redux";
class Todolist extends Component{
render() {
return (
<div>
<div>
<input value={this.state.inputValues}></input>
<button>提交</button>
</div>
<ul>
<li>持续学习</li>
</ul>
</div>
)
}
}
export default connect(null,null)(Todolist);意思是令store与Todolist做链接
这里的Todolist是个UI组件,connect返回的是一个容器组件
mapStateToprops方法:将外部的数据(即state对象)转换为UI组件的标签属性
import React, { Component } from "react";
import store from "./store/index.js";
import { connect } from "react-redux";
class Todolist extends Component{
render() {
return (
<div>
<div>
<input value={this.props.inputValue}></input>
<button>提交</button>
</div>
<ul>
<li>持续学习</li>
</ul>
</div>
)
}
}
//下面的state是store的state
//这个方法的含义,就是可以把store的state映射到组件的props
const mapStateToProps= (state) => {
return {
inputValue: state.inputValue
}
}
export default connect(mapStateToProps,null)(Todolist);
mapDispatchToProps方法,将store.dispatch与组件的props挂钩
- 将本应在Todolist体内定义的handleinputValue函数定义在mapDispatchToProps
- 修改input的属性:
onChange={this.handleinputValue.bind(this)}
变为onChange={this.props.handleInputChange}
- 删除import store from “…”
import React, { Component } from "react";
import { connect } from "react-redux";
class Todolist extends Component{
render() {
return (
<div>
<div>
<input onChange={this.props.handleInputChange} value={this.props.inputValue}></input>
<button>提交</button>
</div>
<ul>
<li>持续学习</li>
</ul>
</div>
)
}
}
//下面的state是store的state
//这个方法的含义,就是可以把store的state映射到组件的props
const mapStateToProps= (state) => {
return {
inputValue: state.inputValue
}
}
映射store.dispatch到proprs上
const mapDispatchToProps=(dispatch)=>{
return {
handleInputChange(e) {
let data = e.target.value;
const action = {
type: "get_input_value",
data
}
dispatch(action);
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Todolist);