• react组件通信


    1 props传值

    1.1 思路

    渲染列表:App--->LIst  (数据放哪?自己--state;某些--父组件state--->app组件定义共享数组)

    添加:header--->App:this.props.add()   onKeyUp

    移入:加一个移入状态的标识控制是否显示  onMouseEnter/onMouseLeave

    勾选:Item--->App:this.props.updateItem()

    删除:Item--->App:this.props.delItem()

    全选:Footer--->App:onChange(全选/取消)+checked(勾选数=总数)

    1.2 编码

    父组件向子组件传值;

    子组件调用父组件方法。

    父组件

    1. // 方法
    2. addTodo = (todoObj) => {
    3. const { todos } = this.state
    4. const newTodos = [todoObj, ...todos]
    5. this.setState({
    6. todos: newTodos
    7. })
    8. }
    9. //数据
    10. state = {
    11. todos: [
    12. { id: '001', name: '吃饭', done: true },
    13. { id: '002', name: '睡觉', done: true },
    14. { id: '003', name: '打代码', done: false },
    15. { id: '004', name: '逛街', done: false }
    16. ]
    17. }
    18. render () {
    19. const { todos } = this.state
    20. return (
    21. <div className="todo-container">
    22. <Header addTodo={this.addTodo} todos={this.state.todos}/>
    23. </div>
    24. </div >
    25. )
    26. }

     子组件

    1. import { PropTypes } from 'prop-types'
    2. //接收父组件函数
    3. static propsTypes = {
    4. addTodo: PropTypes.func.isRequied
    5. }
    6. //子组件调用父组件方法
    7. addTodo = (event) => {
    8. //...
    9. this.props.addTodo(todoItem)
    10. }
    11. render () {
    12. //接收父组件数据
    13. const { todos} = this.props
    14. return (
    15. <div className="todo-header">
    16. <input type="text" placeholder="请输入你的任务名称,按回车键确认" onKeyUp={this.addTodo} />
    17. </div>
    18. )
    19. }

    2 PubSub

    适用于任意组件通信

    1. import PubSub from 'pubsub-js'
    2. //发布
    3. PubSub.publish('updateList', data)
    4. //订阅
    5. componentDidMount () {
    6. this.token = PubSub.subscribe('updateList', (_, data) => {
    7. console.log(data, '接受的数据');
    8. console.log(_, '第一个参数');
    9. })
    10. }
    11. //取消订阅
    12. componentWillUnmount () {
    13. PubSub.unsubscribe(this.token);
    14. }

    3 redux

    3.1 简介

    redux:状态管理(共享状态、组件通信 )

    3.2 编码

    3.2.1 Count.jsx(组件)

    1. import store from './redux/store'
    2. import { createDecrementAction } from './redux/action'
    3. //取值
    4. const count = store.getState();
    5. if (count % 2 === 1) {
    6. //分发
    7. store.dispatch(createIncrementAction(value * 1))
    8. }
    9. componentDidMount () {
    10. //检测redux中状态的变化,只要变化,就调用render
    11. store.subscribe(() => {
    12. this.setState({})
    13. })
    14. }

    3.2.2 redux/constant.js

    1. export const INCREMENT = 'increment'
    2. export const DECREMENT = 'decrement'

    3.2.3 redux/action.js

    1. import { INCREMENT, DECREMENT } from './constant'
    2. //同步action,值为一般对象
    3. export const createIncrementAction = data => ({ type: INCREMENT, data })
    4. export const createDecrementAction = data => ({ type: DECREMENT, data })
    5. //异步action,值为函数。异步任务有结果后,分发一个同步action操作数据。不是必须要用的,可放在组件中。
    6. export const createIncrementAsyncAction = (data, time) => {
    7. return (dispatch) => {
    8. setTimeout(() => {
    9. dispatch(createIncrementAction(data))
    10. },time)
    11. }
    12. }

    3.2.4 redux/reducer.js

    1. import {INCREMENT,DECREMENT} from './constant'
    2. const initState = 0
    3. export default function countReducer (preState = initState, action) {//reducer函数会接到两个参数:之前的状态(preState),动作对象(action)
    4. console.log(preState,action,'初始化');//0 {type: '@@redux/INIT2.0.y.s.0.h'}
    5. const { type, data } = action
    6. switch (type) {
    7. case INCREMENT:
    8. return preState + data
    9. case DECREMENT:
    10. return preState - data
    11. default:
    12. return preState
    13. }
    14. }

    3.2.5 redux/store.js

    1. import { createStore,applyMiddleware,combineReducers } from 'redux'
    2. import countReducer from './reducer'
    3. // 用于支持异步action
    4. import thunk from 'redux-thunk'
    5. //引入redux-devtools-extension
    6. import {composeWithDevTools} from 'redux-devtools-extension'
    7. //汇总reducer:实现数据共享
    8. const allReducer = combineReducers({
    9. he: countReducer,
    10. rens:personReducer
    11. })
    12. // 暴露一个store对象
    13. export default createStore(allReducer ,composeWithDevTools(applyMiddleware(thunk)))

    react-redux

    4.1 原理

    4.2 编码

    4.2.1 index.js

    1. import React from 'react';
    2. import ReactDOM from 'react-dom/client';
    3. import App from './App';
    4. import store from './redux/store'
    5. import {Provider} from 'react-redux'
    6. const root = ReactDOM.createRoot(document.getElementById('root'));
    7. root.render(
    8. <React.StrictMode>
    9. {/* 统一传一次store,无需在APP中多次传递store,让App所有的后代容器组件都能接收到store */}
    10. <Provider store={store}>
    11. <App />
    12. </Provider>
    13. </React.StrictMode>
    14. );

    4.2.2 Count.jsx(容器组件)

    1. import { createIncrementAction } from './redux/action'
    2. import { connect } from 'react-redux'
    3. class Count extends Component {
    4. incrementIfOdd = () => {
    5. const { value } = this.selectNum
    6. if (this.props.count % 2 === 1) {//取值
    7. this.props.jia(value * 1)//分发
    8. }
    9. }
    10. }
    11. //写法一
    12. const mapStateToProps = (state) => {//用于传递状态
    13. return { count: state.he }//传递给UI组件props
    14. }
    15. const mapDispatchToProps = (dispatch) => {//用于传递操作状态的方法
    16. return {//传递给UI组件props
    17. jia: number => dispatch(createIncrementAction(number)),
    18. jian: number => dispatch(createDecrementAction(number)),
    19. jiaAsync: (number, time) => dispatch(createIncrementAsyncAction(number, time)),
    20. }
    21. }
    22. //暴露一个Count的容器组件
    23. export default connect(mapStateToProps, mapDispatchToProps)(Count)
    24. // 写法二:简写
    25. export default connect(
    26. state => ({ count: state }),
    27. // 函数写法1:语法简写
    28. // dispatch => ({
    29. // jia: number => dispatch(createIncrementAction(number)),
    30. // jian: number => dispatch(createDecrementAction(number)),
    31. // jiaAsync: (number, time) => dispatch(createIncrementAsyncAction(number, time)),
    32. // })
    33. // 对象写法2:dispatch由react分发
    34. {
    35. jia: createIncrementAction,
    36. jian: createDecrementAction,
    37. jiaAsync: createIncrementAsyncAction,
    38. }
    39. )(Count)

    redux/constant.js

    同上

    redux/action.js

    同上

    redux/reducer.js

    同上

    redux/store.js

    同上

  • 相关阅读:
    刘韧:接近聪明人最容易变聪明
    单调栈题目:最大矩形
    【Python】 Python 文件与路径处理
    第12章 企业应用部署
    【必备】用VSCode开发Vue程序必备插件之一Vue Language Features (Volar)
    springboot+vue3+elementui plus汽车租赁网站源码
    树莓派串口通信常用函数
    使用Transient noise和ac noise仿真晶体管噪声
    华为云之深入探究GaussDB如何助力企业公司打造金融核心数据
    ReentrantLock 源码
  • 原文地址:https://blog.csdn.net/weixin_46151381/article/details/125406616