redux
redux也是一个架构思维, 在这个架构思维中 React 充当是 视图 V
redux使用流程 ( todolist – 增加一条数据 )
- redux是一个架构思维,我们实现需要一个工具,这个工具叫做redux
- 安装redux
$ yarn add redux
- 在src下新建一个store,store中新建index.js用来打造store
import { createStore } from 'redux'
import reducer from './reducer'
const store = createStore( reducer ) // 不加new createStore() 参数不是一个 Object 而是一个Function
export default store
- 在store下新建一个state
const state = {
todos: [
{
id: 1,
task: '任务一'
}
]
}
export default state
- 在 store下新建一个 reducer
import state from './state'
const reducer = ( previousState = state , action ) => {
const newState = {
...previousState // 解构的原因是为了做深拷贝,我们操作newState,不会影响state
}
}
export default reducer
- 在你想要使用的组件中直接引用 store
import React, { Component,Fragment } from 'react'
import store from '../store'
class Content extends Component{
constructor () {
super()
this.state = {
todos: store.getState().todos
}
}
render () {
return (
<Fragment>
<div>
<ul>
<li> 1 </li>
</ul>
</div>
</Fragment>
)
}
}
export default Content
-
进行用户交互 React component — > actionCreators
-
在store下新建 actionCreators.js
import * as type from './type'
import store from './index'
const actionCreators = {
add_todos_item ( val ) {
//动作的创建
const action = {
type: type.ADD_TODOS_ITEM,
payload: val // 负载数据
}
// 动作的发送
store.dispatch( action )
}
}
export default actionCreators
- 在Button组件中触发 actionCreators中 的方法
import React, { Component,Fragment } from 'react'
import actionCreators from './../store/actionCreators';
class Button extends Component{
add = () => {
let val = this.input.value
actionCreators.add_todos_item( val )
this.input.value = ''
}
render () {
return (
<Fragment>
<div>
<input type = "text" ref = { el => this.input = el } />
<br/>
<button onClick = { this.add }> + </button>
</div>
</Fragment>
)
}
}
export default Button
- 在 reducer中修改数据
import state from './state'
// const state = require( './state' )
import * as type from './type'
const reducer = ( previousState = state,action) => {
let newState = {
...previousState
}
//判断用户进行了那个用户交互 ,操作新状态
switch ( action.type ) {
case type.ADD_TODOS_ITEM:
//修改新状态
newState.todos.push({
id: newState.todos.length + 1,
task: action.payload
})
break;
default:
break;
}
return newState
}
export default reducer
- 进行数据个更新,通过store的订阅功能进行更新,也就是组件需要重新赋值一次数据
- 在Content组件中进行订阅
componentDidMount () {
store.subscribe( () => {
this.setState({
todos: store.getState().todos
})
})
}
14.进行页面渲染
const Item = ( props ) => {
return <li> {props.task} </li>
}
renderItem = () => {
return this.state.todos.map( item => {
return <Item {...item} key = {item.id}></Item>
})
}
<ul>
{ this.renderItem() }
</ul>