目录

状态提升 (共享状态)

# 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 的那个组件。

上次更新: 2023/07/11, 15:43:07
最近更新
01
基本知识
07-18
02
卷积神经网络识别图像
07-18
03
损失函数
07-18
更多文章>