Wang's blog Wang's blog
首页
  • 前端文章

    • HTML教程
    • CSS
    • JavaScript
  • 前端框架

    • Vue
    • React
    • VuePress
    • Electron
  • 后端技术

    • Npm
    • Node
    • TypeScript
  • 编程规范

    • 规范
  • 我的笔记
  • Git
  • GitHub
  • VSCode
  • Mac工具
  • 数据库
  • Google
  • 服务器
  • Python爬虫
  • 前端教程
更多
收藏
关于
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Wang Mings

跟随大神,成为大神!
首页
  • 前端文章

    • HTML教程
    • CSS
    • JavaScript
  • 前端框架

    • Vue
    • React
    • VuePress
    • Electron
  • 后端技术

    • Npm
    • Node
    • TypeScript
  • 编程规范

    • 规范
  • 我的笔记
  • Git
  • GitHub
  • VSCode
  • Mac工具
  • 数据库
  • Google
  • 服务器
  • Python爬虫
  • 前端教程
更多
收藏
关于
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • CSS

  • Npm

  • Vue

  • HTML

  • Node

  • Yaml

  • React

    • ReactUI组件库
    • react实战技巧经验
    • react-pdf预览PDF文件
    • react常见的一些报错
    • Hook

    • 核心概念

      • 表单
      • JSX简介
      • 列表&Key
      • 组件&Props
      • 事件处理
      • 元素渲染
      • 条件渲染
      • 组合vs继承
      • State&生命周期
      • 状态提升(共享状态)
        • React哲学(编写一个复杂组件的原则)
      • 案例演示

      • 高级指引

    • 框架

    • 规范

    • Electron

    • JS演示

    • VuePress

    • JavaScript

    • TypeScript

    • 微信小程序

    • TypeScript-axios

    • 前端
    • React
    • 核心概念
    wangmings
    2022-07-19
    目录

    状态提升(共享状态)

    # 09. 状态提升 (共享状态)

    通常,多个组件需要反映相同的变化数据,这时我们建议将共享状态提升到最近的共同父组件中去。

    在 React 中,将多个组件中需要共享的 state 向上移动到它们的最近共同父组件中,便可实现共享 state。这就是所谓的“状态提升”

    两个输入框共享数据的例子:

    const scaleNames = {
      c: '摄氏度',
      f: '华氏度'
    };
    
    // 转摄氏度
    function toCelsius(fahrenheit) {
      return (fahrenheit - 32) * 5 / 9;
    }
    
    // 转华氏度
    function toFahrenheit(celsius) {
      return (celsius * 9 / 5) + 32;
    }
    
    // 转换,为空时返回空,否则返回保留三位小数的浮点数
    function tryConvert(temperature, convert) {
      const input = parseFloat(temperature);
      if (Number.isNaN(input)) {
        return '';
      }
      const output = convert(input);
      // Math.round返回一个数字四舍五入后的整数
      const rounded = Math.round(output * 1000) / 1000;
      return rounded.toString();
    }
    
    // 水是否会沸腾
    function BoilingVerdict(props) {
      if (props.celsius >= 100) {
        return <p>水会沸腾.</p>;
      }
      return <p>水不会沸腾.</p>;
    }
    
    // 子组件 - 输入框
    class TemperatureInput extends React.Component {
      constructor(props) {
        super(props); // 接收父组件传入props
        this.handleChange = this.handleChange.bind(this); // 绑定回调函数,并修正this
      }
    	
      // 处理change
      handleChange(e) {
        // e是合成事件对象,通过e.target.value 取值
        // 调用父组件传入的onTemperatureChange函数,并传值
        this.props.onTemperatureChange(e.target.value);
        
        // 当子组件输入框值改变时调用父组件的onTemperatureChange方法,并传出值。
        // 另外,onTemperatureChange命名方式:`在<子组件>变更`
      }
    
      render() {
        // 接收父组件传入的温度值
        const temperature = this.props.temperature;
        // 接收父组件传入的衡量方式
        const scale = this.props.scale;
        
        return (
          <fieldset>
            <legend>输入温度-{scaleNames[scale]}:</legend>
            <input value={temperature}
                   onChange={this.handleChange} />
          </fieldset>
        );
      }
    }
    
    
    // 父组件 - 计算器
    class Calculator extends React.Component {
      constructor(props) {
        super(props); // 接收父组件传入props
        
        // 绑定事件回调,并修正this
        this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
        this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
        // 创建初始状态值
        this.state = {temperature: '', scale: 'c'};
      }
    	
      // 处理`摄氏度`变更
      handleCelsiusChange(temperature) {
        // temperature接收到子组件传来的参数,并通过setState修改状态
        this.setState({scale: 'c', temperature});
      }
    	
      // 处理`华氏度`变更
      handleFahrenheitChange(temperature) {
        // temperature接收到子组件传来的参数,并通过setState修改状态
        this.setState({scale: 'f', temperature});
      }
    	
      // 渲染函数(每当state改变都会调用)
      render() {
        // 取得当前state下的值
        const scale = this.state.scale;
        const temperature = this.state.temperature;
        
        // 根据scale值取得相应的温度数据
        const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
        const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
    		
        // 返回渲染的元素
        // 插入子组件TemperatureInput传入相应的参数,onTemperatureChange指定为当前组件的回调函数
        return (
          <div>
            <TemperatureInput
              scale="c"
              temperature={celsius}
              onTemperatureChange={this.handleCelsiusChange} />
            <TemperatureInput
              scale="f"
              temperature={fahrenheit}
              onTemperatureChange={this.handleFahrenheitChange} />
            <BoilingVerdict
              celsius={parseFloat(celsius)} />
          </div>
        );
      }
    }
    
    // 渲染DOM
    ReactDOM.render(
      <Calculator />,
      document.getElementById('root')
    );
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127

    在 CodePen 上尝试 (opens new window)

    笔记

    1. 父组件给所有子组件传入state的值
    2. 子组件修改值时调用父组件的方法并把值传出
    3. 父组件接收到值之后修改state
    4. state被修改之后重新执行render函数,并回到第1步

    # 小结

    • 任何可变数据应当只有一个相对应的唯一“数据源”

      • 通常,state 都是首先添加到需要渲染数据的组件中去
      • 然后,如果其他组件也需要这个 state,那么你可以将它提升至这些组件的最近共同父组件中
      • 你应当依靠自上而下的数据流 (opens new window),而不是尝试在不同组件间同步 state。
    • “存在”于组件中的任何 state,仅有组件自己能够修改它

    • 如果某些数据可以由 props 或 state 推导得出,那么它就不应该存在于 state 中。(如上例中,经过tryConvert方法转换的后的值。)

    # React开发者工具(debug)

    当你在 UI 中发现错误时,可以使用 React 开发者工具 (opens new window) 来检查问题组件的 props,并且按照组件树结构逐级向上搜寻,直到定位到负责更新 state 的那个组件。

    编辑 (opens new window)
    State&生命周期
    React哲学(编写一个复杂组件的原则)

    ← State&生命周期 React哲学(编写一个复杂组件的原则)→

    最近更新
    01
    theme-vdoing-blog博客静态编译问题
    09-16
    02
    搜索引擎
    07-19
    03
    友情链接
    07-19
    更多文章>
    Theme by Vdoing | Copyright © 2019-2022 Evan Xu | MIT License
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式