下载
npm install react-redux
React-Redux 是 Redux 的官方 React 绑定库。它能够使你的 React 组件从 Redux store 中读取数据,并且向 store 分发 actions 以更新数据
React-Redux 将所有组件分成两大类:UI 组件和容器组件。UI 组件负责 UI 的呈现,容器组件负责管理数据和逻辑。
UI 组件:只负责 UI 的呈现,不带有任何业务逻辑;没有状态(即不使用 this.state 这个变量);所有数据都由参数 this.props 提供;不使用任何 Redux 的 API
容器组件:负责管理数据和业务逻辑,不负责 UI 的呈现;带有内部状态;使用 Redux 的 API。
React-Redux 规定,所有的 UI 组件都由用户提供,容器组件则是由 React-Redux 自动生成。也就是说,用户负责视觉层,状态管理则是全部交给它。
connect()
import React from "react";
// import store from '../store'
// 连接器
import {
connect } from 'react-redux'
import {
changeInputAction,
addItemAction,
detelclickAction
} from '../store/reducercreateor'
import {
change_input,
add_item,
dete
} from '../store/reduceType'
const todoList = (props) => {
let {
inputValue, changeHandler, clickHandler, detelclick } = props
return (
<div>
<div>
<input type="text" placeholder= {
inputValue }
onChange={
changeHandler }
value= {
inputValue }/>
<button onClick={
clickHandler}>提交</button>
</div>
<ul>
{
props?.list?.map((item,index) => {
return (
<li key={
index} onClick= {
(index) => {
detelclick(index)}}>{
item }</li>
)
})
}
</ul>
</div>
)
}
const StateToProps = (state) => {
return {
inputValue: state.inputValue,
list: state.list
}
}
const dispatchToProps = (dispatch) => {
return {
changeHandler (e) {
dispatch(changeInputAction(change_input, e.target.value))
},
clickHandler (e) {
dispatch(addItemAction(add_item, e.target.value))
},
detelclick (index) {
console.log(index)
dispatch(detelclickAction(dete, index))
}
}
}
// 映射关系
export default connect(StateToProps, dispatchToProps)(todoList)
在redux中的写法
import {
change_input,
add_item,
dete
} from './reduceType'
const defaultState = {
inputValue: '请在输入框输入',
list: []
}
// eslint-disable-next-line import/no-anonymous-default-export
export default (state= defaultState, action) => {
console.log(state, action)
let newState = JSON.parse(JSON.stringify(state))
if (action.type === change_input) {
newState.inputValue = action.value
return newState
}
if (action.type === add_item) {
newState.list.push(newState.inputValue)
newState.inputValue = ''
return newState
}
if (action.type === dete) {
newState.list.splice(action.index, 1)
return newState
}
return state
}
reduceType.js中声明类型
const change_input = 'change_input'
const add_item = 'add_item'
const dete = 'dete'
export {
change_input,
add_item,
dete
}