我是靠谱客的博主 仁爱花瓣,最近开发中收集的这篇文章主要介绍react-redux多组件之间数据共享,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

(1).定义一个Pserson组件,和Count组件通过redux共享数据。
(2).为Person组件编写:reducer、action,配置constant常量。
(3).重点:Person的reducer和Count的Reducer要使用combineReducers进行合并,
		合并后的总状态是一个对象!!!
(4).交给store的是总reducer,最后注意在组件中取出状态的时候,记得“取到位”。

在这里插入图片描述
整体文件目录结构
在这里插入图片描述

让store 文件为多个组件服务
需要用到的是 combineReducers
例如:
// 汇总所有reducer变为一个总的reducer
const allReducer = combineReducers({
he: countReducer,
rens: personReducer
})

/* 
  该文件用于暴露一个store 对象,整个应用只能有一个store对象
*/
// 引入 creacteStore 专门用于创建redux 中最为核心的store 对象
import { createStore,applyMiddleware ,combineReducers} from 'redux'
import thunk from 'redux-thunk'

// 引入为Count组件服务的reducer
import countReducer from './reducers/count'
// 引入为Count组件服务的reducer
import personReducer from './reducers/person'

// 汇总所有reducer变为一个总的reducer
const allReducer = combineReducers({
  he: countReducer,
  rens: personReducer
})

// 暴露store
export default createStore(allReducer,applyMiddleware(thunk))        

然后就可以在组件中调用state来获取想要的数据了
export default connect(
state => ({ yiduiren: state.rens,he:state.he }),//映射状态
{jiayiren:createAddPersibAction}
)(Person)

import React, { Component} from 'react'
import { nanoid } from 'nanoid'
import { connect } from 'react-redux'
import {createAddPersibAction} from '../../redux/actions/person'
class Person extends Component {
  addPerson=()=> {
    const name= this.nameNode.value
    const age = this.ageNode.value
    const personObj = { id: nanoid(), name, age }
    // console.log(personObj);
    this.props.jiayiren(personObj)
    this.nameNode.value = ''
    this.ageNode.value=''
  }
  render() {
    return (
      <div>
        <h2>我是Person组件,上方组件求和为{this.props.he}</h2>
        <input ref={c => this.nameNode = c} type="text" placeholder = "输入名字"/>
        <input ref={c => this.ageNode = c} type="text" placeholder="输入年龄" />
        <button onClick={this.addPerson}>添加</button>
        <ul>
          {
            this.props.yiduiren.map(p => {
              return <li id = {p.id }>{p.name}---{p.age}</li>
            })
          }
        </ul>
      </div>
    )
  }
}

export default connect(
  state => ({ yiduiren: state.rens,he:state.he }),//映射状态
  {jiayiren:createAddPersibAction}
)(Person)

最后

以上就是仁爱花瓣为你收集整理的react-redux多组件之间数据共享的全部内容,希望文章能够帮你解决react-redux多组件之间数据共享所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部