react-redux 的使用

react-redux

React Redux 是 Redux 的官方 React UI 绑定库。它使得你的 React 组件能够从 Redux store 中读取到数据,并且你可以通过dispatch actions去更新 store 中的 state

安装

npm install --save react-redux

Provider

React Redux 包含一个 组件,这使得 Redux store 能够在应用的其他地方使用

改造 index.js 页面,引入Provider

import { Provider } from 'react-redux'
import store from './store'

通过 Provider 组件将 store 放在了全局的组件可以够得到的地方


   
 

connect

  1. connect 方法会帮助我们订阅 store ,当 store 中的状态发生更改的时候,会帮助我们重新渲染组件
  2. connect 方法会让我们获取 store 中的状态,将状态通过组件的 props 属性映射给组件
  3. connect 方法可以让我们获取 dispatch 方法

引入connect

import { connect } from 'react-redux'

connect 有两个值,一个是 mapStateToProps ,用于将 state 的数据通过 props 属性映射给组件

const mapStateToProps = state => ({
  list: state.list
})

一个是 mapDispatchToProps ,让我们获取 dispatch 方法,可以将方法映射组件

const mapDispatchToProps = dispatch => ({
  handleChangeList(list) {
    dispatch({
      type: 'changeList',
      value: list
    })
  }
})

最后指定要映射的组件

connect(mapStateToProps, mapDispatchToProps)(TotoList);

这样我们就能在组件 TotoList 使用属性和方法了

完整代码

import React, { useRef, useState, startTransition } from 'react';
import { connect } from 'react-redux'

const TotoList = ({ list, handleChangeList }) => {
  const inputRef = useRef()

  const [value, setValue] = useState('')

  const items = list.map((item, index) => {
    return (

{item} handledel(index)}> 删除

) }) const handleChange = () => { startTransition(() => { setValue(inputRef.current.value) }) } const handleAdd = () => { let newList = [...list] newList.push(inputRef.current.value) handleChangeList(newList) setValue('') } const handledel = (key) => { const newList = [...list] newList.splice(key, 1) handleChangeList(newList) } return (
{items}
) } const mapDispatchToProps = dispatch => ({ handleChangeList(list) { dispatch({ type: 'changeList', value: list }) } }) const mapStateToProps = state => ({ list: state.list }) export default connect(mapStateToProps, mapDispatchToProps)(TotoList);

你可能感兴趣的:(react,react.js,前端,前端框架)