官方react-redux基本使用

171 阅读2分钟

react官方出品的redux跨组件传值

image.png


UI组件

Count.jsx

import React, { Component } from "react"; 
// 引入acrion import { increment, decrement, incrementAsync } from "../../redux/actions/count"; 
//connect import { connect } from "react-redux"; 
class Count extends Component {   
constructor(props) {     
super(props);     
this.state = {};   }   
increment = () => {     
const { value } = this.selectNumber;     
this.props.increment(value * 1);   };   
decrement = () => {     
const { value } = this.selectNumber;     
this.props.decrement(value * 1);   };   
//奇数加   
incrementIfOdd = () => {     
const { value } = this.selectNumber;     
if (this.props.count % 2 !== 0) {       
this.props.increment(value * 1);     }   };   
//异步加   
incrementAync = () => {     
const { value } = this.selectNumber;     
this.props.incrementAsync(value * 1, 1000);   };   
render() {     
return (       
<div>         
<h2>Count组件,下方总人数为{this.props.personCount}</h2>         
<h4>当前求和{this.props.count}</h4>         
<select ref={(c) => (this.selectNumber = c)}>           
<option value="1">1</option>           
<option value="2">2</option>           
<option value="3">3</option>         
</select>                   
<button onClick={this.decrement}>-</button>          
<button onClick={this.increment}>+</button>          
<button onClick={this.incrementIfOdd}>当前和为奇数再+</button>          <button onClick={this.incrementAync}>异步+</button>        
</div>     );   } } 
//使用connect创建一个count容器 
export default connect(   
(state) => ({     
count: state.count,     
personCount: state.person.length,   }),   
{     
increment,     
decrement,     
incrementAsync,   
} )(Count); 


Person--index.jsx

import React, { Component } from "react";
import { nanoid } from "nanoid";
// 引入acrion
import { addPerson } from "../../redux/actions/person";
//connect
import { connect } from "react-redux";

class Person extends Component {
  addPerson = () => {
    const name =  this.nameNode.value;
    const age =  this.ageNode.value;
    const personObj = {id:nanoid(),name,age}
    this.props.addPerson(personObj)
    this.nameNode.value = ''
    this.ageNode.value = ''
    console.log('this.props.person--',this.props.person);
  };
  render() {
    return (
      <div>
        <h2>Person 上方count的和为{this.props.count}</h2>
        <input
          type="text"
          ref={(c) => (this.nameNode = c)}
          placeholder="请输入名字"
        />
        <input
          type="text"
          ref={(c) => (this.ageNode = c)}
          placeholder="请输入年龄"
        />
        <button onClick={this.addPerson}> 添加 </button>
        <ul>
          {this.props.person.map((p) => {
            return (
              <li key={p.id}>
                {p.name}--{p.age}
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}

export default connect(
  state =>({
    person:state.person,
    count:state.count
  }),
  {addPerson}//映射操作状态的方法
)(Person);

action :count

import {INCREMENT,DECREMENT} from '../constants';
export const increment = data => ({type:INCREMENT,data})
export const decrement = data => ({type:DECREMENT,data})

export const incrementAsync = (data,time)=>{
    return  (dispatch) => {
        setTimeout(() => {
            dispatch(increment(data))
        }, time)
    }
}
//ok

action : person


import {ADD_PERSON} from '../constants';

export const addPerson = personObj => ({
    type:ADD_PERSON,
    data:personObj
})
//ok

redcer: count

import {INCREMENT,DECREMENT} from '../constants';
//初始化人员列表
const initState = 0
export default function countReducer(preState=initState , action ){
    const {type,data} = action
    switch(type){
        case INCREMENT:
            return preState + data*1
        case DECREMENT:
            return  preState - data*1
        default:
        return preState
    }
}

redcer: person

import {ADD_PERSON} from "../constants";
const initState = [{ id:'001',name: "tom", age: 18 }];
export default function personReducer(preState = initState, action) {
    const{type,data}=action
    switch(type){
        case ADD_PERSON:
            return [data,...preState]
        default :
        return preState
    }
}

//ok

redcer: index

import {combineReducers} from 'redux';

//引入Count的reducer
import count from './count';
//引入Person的reducer
import person from './person';
//汇总所有reducer
export default  combineReducers({
    count,
    person
})
//ok

constants定义常量

export const INCREMENT  = 'increment'
export const DECREMENT  = 'decrement'
export const ADD_PERSON  = 'add_person'
//ok

APP.js


import logo from './logo.svg';
import './App.css';
import Count from './containers/Count/'
import Person from './containers/Person'
function App() {
  return (
    <div className="App">
      <Count/>
      <hr/>
      <Person/>
    </div>
  );
}

export default App;

入口文件index.js

import React from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import './index.css';
import App from './App';
import store from './redux/store';
import {Provider} from 'react-redux';

ReactDOM.render(
  <Provider store={store}>
    <App />,
  </Provider>,
  document.getElementById('root')
);

reportWebVitals();


安装的插件:

image.png

总结

image.png