美文网首页
React入门(七)Redux(二)

React入门(七)Redux(二)

作者: 我拥抱着我的未来 | 来源:发表于2019-03-17 21:37 被阅读0次

本文内容

  • 概述Redux原理
  • 总结Redux使用

(一)概述Redux原理

个人理解Redux 里面由两部分组成
store 仓库用来存放reducer和state
reducer 是用来处理数据的。

reducer里面要接受两个参数

(1) state 公共数据
(2) action用来操作数据
action 里面要有两个参数
第一个参数就是 type
第二个参数就是要修改的值
类型
{
types:"xxxxx",
value
}

(二)Redux使用

(i) action 拆分成两个文件

(1) types
export const CHANGE_LIST = 'change_list'
export const CHANGE_VALUE = 'change_value'
export const DELETE_ONE = 'delete_one'
(2) action合并

action 实际上就是很多个对象

import * as actionType from './actionType'
export const changelist = () => {
  return {
    type: actionType.CHANGE_LIST
  }
}
export const changeValue = value => {
  return {
    type: actionType.CHANGE_VALUE,
    value
  }
}
export const deleteData = index => {
  return {
    type: actionType.DELETE_ONE,
    index
  }
}

(ii) Redux里面

之所以引入types是害怕拼写错误

import * as actionType from './actionType'
const defaultState = {
  inputValue: '',
  list: [
    'Racing car sprays burning fuel into crowd.',
    'Japanese princess to wed commoner.',
    'Australian walks 100km after outback crash.',
    'Man charged over missing wedding girl.',
    'Los Angeles battles huge wildfires.'
  ]
}
export default (state = defaultState, action) => {
  if (action.type === actionType.CHANGE_VALUE) {
    let newDate = JSON.parse(JSON.stringify(state))
    newDate.inputValue = action.value
    console.log(newDate)
    return newDate
  }
  if (action.type === actionType.CHANGE_LIST) {
    let newDate = JSON.parse(JSON.stringify(state))
    newDate.list.push(newDate.inputValue)
    newDate.inputValue = ''
    return newDate
  }
  if (action.type === actionType.DELETE_ONE) {
    let newDate = JSON.parse(JSON.stringify(state))
    newDate.list.splice(action.index, 1)
    return newDate
  }
  return state
}

备注

store 必须是唯一的,不能出现第二个
只有store才能改变自己的内容,所以reducer里面必须返回一个新的对象,而不能直接修改state

常用api

createStore()  // 创建仓库
store.dispatch(action) // 发射子弹
store.getState(); //获取到公共数据
store.subscribe(); // 监听公共数据的变化里面传递的是一个方法

相关文章

网友评论

      本文标题:React入门(七)Redux(二)

      本文链接:https://www.haomeiwen.com/subject/iskpmqtx.html