美文网首页
react-状态管理redux使用

react-状态管理redux使用

作者: 四月的谎言v5 | 来源:发表于2019-07-13 12:48 被阅读0次

完整demo https://gitee.com/siyuev5/react-demo/tree/master/react-demo

有个问题如果是父子组件传值可以通过props 但是如果是父组件和孙孙孙孙孙孙子组件传值呢 是不是要每个组件都通过props传递,如果是跨页面跨组件传值呢,比如购物车那肯定非常麻烦这时候就要用到
redux来管理了。

看看下面2个组件

import React, { Component } from 'react'

export default class MyComponent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      list: ['1', '2']
    }
  }
  render() {
    return (
      <div>
        <ul>
          {this.state.list.map((value, index) => {
            return (
              <li index={index} key={index}>
                {value}
              </li>
            )
          })}
        </ul>
      </div>
    )
  }
}

import React, { Component } from 'react'
import MyConponent from '../components/MyComponent'
export default class MyPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      inputValue: ''
    }
  }
  render() {
    return (
      <div>
        <input
          value={this.state.inputValue}
          onChange={e => this.setState({ inputValue: e.target.value })}
          type="text"
        />
        <input type="button" value="添加" />
        <MyConponent />
      </div>
    )
  }
}

现在问题来了 我怎么在 MyPage 组件中点击按钮把 inputValue 添加到 MyComponent 的list里面 然后渲染出来(不用组件props传值)。


1.png

npm install redux 先安装一波

在src下面创建一个 store 文件夹 在 store 下面创建一个 reduxTest.js 文件 内容如下

import { createStore } from 'redux'

const defaultState = {
  list: []
}
const store = createStore((state = defaultState, action) => {
  console.log(action)
  switch (action.type) {
    case 'ADD_LIST': {
      return {
        ...state,
        list: [...state.list, action.inputValue]
      }
    }
    default:
      break
  }
  return state
})
export default store



主要看看 createStore 第一个参数是一个方法
这个方法的
第一个参数 state 是更改之前的数据state对象
第二个参数 action 组件提交要更改的数据对象

然后MyComponent组件修改一下 如下

import React, { Component } from 'react'
import Store from '../store/reduxTest'
export default class MyComponent extends Component {
  constructor(props) {
    super(props)
    this.state = Store.getState()
    Store.subscribe(this.handleStoreUpdate.bind(this))
  }
  render() {
    return (
      <div>
        <ul>
          {this.state.list.map((value, index) => {
            return (
              <li index={index} key={index}>
                {value}
              </li>
            )
          })}
        </ul>
      </div>
    )
  }
  handleStoreUpdate() {
    this.setState(Store.getState())
  }
}

this.state = store.getState() 注意这一句 就是从 redux 拿到 state 数据
Store.subscribe(this.handleStoreUpdate.bind(this)) 注意这一句 订阅数据的修改

MyPage修改如下

import React, { Component } from 'react'
import MyConponent from '../components/MyComponent'
import Store from '../store/reduxTest'

export default class MyPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      inputValue: ''
    }
  }
  render() {
    return (
      <div>
        <input
          value={this.state.inputValue}
          onChange={e => this.setState({ inputValue: e.target.value })}
          type="text"
        />
        <input type="button" onClick={this.addList.bind(this)} value="添加" />
        <MyConponent />
      </div>
    )
  }
  addList() {
    Store.dispatch({
      type: 'ADD_LIST',
      inputValue: this.state.inputValue
    })
    this.setState({
      inputValue: ''
    })
  }
}

MyPage 新增的按钮 onClick事件

 Store.dispatch({
      type: 'ADD_LIST',
      inputValue: this.state.inputValue
    })

redux中的数据通过 dispatch 提交

还记得最开始这段代码吗

其中判断的 action.type 就是通过 dispatch 提交对象中的 type:'ADD_LIST'

import { createStore } from 'redux'

const defaultState = {
  list: []
}
const store = createStore((state = defaultState, action) => {
  switch (action.type) {
    case 'ADD_LIST': {
      return {
        ...state,
        list: [...state.list, action.inputValue]
      }
    }
    default:
      break
  }
  return state
}, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
export default store

我们下来看看点击数据实现删除怎么做 reduxTest.js 添加下面一段代码
注意 state不能直接修改只能 通过return 返回数据方式让 redux自动变更

case 'DEL_LIST_ITEM': {
      const newList = [...state.list]
      newList.splice(action.index, 1)
      return {
        ...state,
        list: newList
      }
    }

MyComponent 修改如下

import React, { Component } from 'react'
import Store from '../store/reduxTest'
export default class MyComponent extends Component {
  constructor(props) {
    super(props)
    this.state = Store.getState()
    Store.subscribe(this.handleStoreUpdate.bind(this))
  }
  render() {
    return (
      <div>
        <ul>
          {this.state.list.map((value, index) => {
            return (
              <li
                index={index}
                key={index}
                onClick={this.delListItem.bind(this, index)}
              >
                {value}
              </li>
            )
          })}
        </ul>
      </div>
    )
  }
  handleStoreUpdate() {
    this.setState(Store.getState())
  }
  delListItem(index) {
    Store.dispatch({
      type: 'DEL_LIST_ITEM',
      index
    })
  }
}

相关文章

  • react-状态管理redux使用

    完整demo https://gitee.com/siyuev5/react-demo/tree/master/r...

  • react-状态管理react-redux使用

    完整demo https://gitee.com/siyuev5/react-demo/tree/master/r...

  • react-状态管理redux-thunk的使用

    完整 demo https://gitee.com/siyuev5/react-demo/tree/master/...

  • Redux详解

    Redux是什么 Redux 是 JavaScript 状态容器,提供可预测化的状态管理。 什么场景使用Redux...

  • redux入门

    什么是redux Redux 是 JavaScript 状态容器,提供可预测化的状态管理。 什么时候使用redux...

  • react-redux

    redux 全局状态管理 react-redux 优化模块 优化redux的使用过程 通过react-redux ...

  • Redux, React-Redux

    Redux: JavaScript 状态容器,提供可预测化的状态管理 需要使用Redux 的情景: 用户的使用方式...

  • Redux

    Redux状态管理 Redux 是 JavaScript 状态管理容器,提供可预测的状态管理。redux 可以让你...

  • react native架构系列(持续更新中)

    1、使用redux、react-redux、redux-thunk做全局状态管理 redux三大原则单一数据源:整...

  • Redux

    介绍 Redux Redux是一个数据状态管理插件,搭配 React 特别合适,详细的用法可见Redux官网 使用...

网友评论

      本文标题:react-状态管理redux使用

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