export default reducer
更新 store/map.js
代码:
//只需要更新mapDispatch函数即可
//store中的dispatch与组件中props的映射
const mapDispatch = dispatch => {
//此处返回的的组件中的props上的函数
return {
changeValue(value){ //更新value数据的函数
dispatch({
type: ‘change_value’,
value
})
}
}
}
创建 Input/index.jsx
组件:
import React,{Component} from ‘react’
import {connect} from ‘react-redux’
import {mapState,mapDispatch} from ‘…/store/map’
class index extends Component {
//更新value
change(e){
this.props.changeValue(e.target.value)
}
render() {
return (
)
}
}
//当前组件是交给connect管理,在当前组件中就可以使用映射的props对象
export default connect(mapState,mapDispatch)(index)
2.3.2、添加数据
更新 store/reducer.js
代码:
const reducer = (state,action) => {
//更新value的值
if(action.type === ‘change_value’){
let temp = JSON.parse(JSON.stringify(state))
temp.value = action.value
return temp
}
//添加数据
if(action.type === ‘list_add’){
let temp = JSON.parse(JSON.stringify(state))
temp.list.push(temp.value)
temp.value = ‘’
return temp
}
return state
}
export default reducer
更新 store/map.js
代码:
//只需要更新mapDispatch函数即可
//store中的dispatch与组件中props的映射
const mapDispatch = dispatch => {
//此处返回的的组件中的props上的函数
return {
changeValue(value){ //更新value数据的函数
dispatch({
type: ‘change_value’,
value
})
},
listAdd(){ //添加数据
dispatch({
type: ‘list_add’
})
}
}
}
更新 Input/index.jsx
组件:
import React,{Component} from ‘react’
import {connect} from ‘react-redux’
import {mapState,mapDispatch} from ‘…/store/map’
class index extends Component {
//更新value
change(e){
this.props.changeValue(e.target.value)
}
//添加数据
submit(e){
//判断回车事件
if(e.target.charCode === 13){
this.props.listAdd()
}
}
render() {
return (
<input value={this.props.value}
onChange={this.change.bind(this)}
onKeyPress={this.submit.bind(this)}/>
)
}
}
//当前组件是交给connect管理,在当前组件中就可以使用映射的props对象
export default connect(mapState,mapDispatch)(index)
注意:
其他功能的实现过程与添加数据功能类似,使用“自底向上”的流程开发:
reducer --> map --> 自定义组件
2.3.3、引入组件
在 App.jsx
根组件中导入 Input
组件:
import Input from ‘./Input/index.jsx’
function App() {
return (
)
}
export default App
在 index.js
入口文件中导入 react-redux
中的 Provider
组件来统一管理 store
对象:
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import App from ‘./App’;
import {Provider} from ‘react-redux’
import store from ‘./store’
ReactDOM.render(
最后
编程基础的初级开发者,计算机科学专业的学生,以及平时没怎么利用过数据结构与算法的开发人员希望复习这些概念为下次技术面试做准备。或者想学习一些计算机科学的基本概念,以优化代码,提高编程技能。这份笔记都是可以作为参考的。