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)
经验分享 程序员 微信小程序 职场和发展