React官网学习实践 - 状态提升

使用 react 经常会遇到几个组件需要共用状态数据的情况。这种情况下,我们最好将这部分共享的状态提升至他们最近的父组件当中进行管理。
我们会创建一个温度计算器来计算水是否会在给定的温度下烧开。


2789632-587b33de3f68fb25.gif

开始呢,我们先创建一个名为 BoilingVerdict 的组件。它会接受 celsius 这个温度变量作为它的 prop 属性,最后根据温度判断返回内容:

function BoilingVerdict(props) {
    if (props.celsius >= 100) {
        return <p>水会烧开</p>;
    }
    return <p>水不会烧开</p>;
}

接下来,我们写一个组件。它会渲染一个 <input> 来接受用户输入,然后将输入的温度值保存在 this.state.temperature 当中。
实现code:

import React, { Component } from 'react';
import './App.css';

function BoilingVerdict(props) {
    if (props.celsius >= 100) {
        return <p>水会烧开</p>;
    }
    return <p>水不会烧开</p>;
}

class App extends Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.state = {temperature: ''};
    }
    handleChange(e) {
        this.setState({temperature: e.target.value});
    }

    componentWillMount () {
        console.log('this is in componentWillMount method.');

    }
    componentDidMount () {
        console.log('this is in componentDidMount method.');
    }
    componentWillReceiveProps (nextProps) {
        console.log('this is in componentWillReceiveProps method.');
    }
    // shouldComponentUpdate (nextProps,nextState) {
    //     console.log('this is in shouldComponentUpdate method.');
    // }
    componentWillUpdate (nextProps,nextState) {
        console.log('this is in componentWillUpdate method.');
    }
    componentDidUpdate (prevProps,prevState) {
        console.log('this is in componentDidUpdate method.');
    }

    render() {
        const temperature = this.state.temperature;
        return (
            <fieldset>
                <legend>输入一个摄氏温度</legend>
                <input
                    value={temperature}
                    onChange={this.handleChange} />
                <BoilingVerdict
                    celsius={parseFloat(temperature)} />
            </fieldset>
        );
  }
    componentWillUnmount () {
        console.log('this is in componentWillUnmount method.');
    }
}

export default App;

状态提升,就是将公用数据变量提升到父组件中。
注意一些方法的使用:
在我们改写 Calculator 组件之前,我们先花点时间总结下 TemperatureInput 组件的改变。我们将其自身的 state 从组件中移除,使用 this.props.temperature 替代 this.state.temperature ,当我们想要响应数据改变时,使用父组件提供的 this.props.onTemperatureChange() 而不是this.setState() 方法:


2789632-93373f3c768d39a5.gif

Code:

import React, { Component } from 'react';
import './App.css';

const scaleNames = {
    c: 'Celsius',
    f: 'Fahrenheit'
};
function BoilingVerdict(props) {
    if (props.celsius >= 100) {
        return <p>水会烧开</p>;
    }
    return <p>水不会烧开</p>;
}
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);
    const rounded = Math.round(output * 1000) / 1000;
    return rounded.toString();
}

class TemperatureInput extends React.Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(e) {
        this.props.onTemperatureChange(e.target.value);
    }

    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 App extends Component {
    constructor(props) {
        super(props);
        this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
        this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
        this.state = {temperature: '', scale: 'c'};
    }

    handleCelsiusChange(temperature) {
        this.setState({scale: 'c', temperature});
    }

    handleFahrenheitChange(temperature) {
        this.setState({scale: 'f', temperature});
    }
    render() {
        const scale = this.state.scale;
        const temperature = this.state.temperature;
        const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
        const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
        return (
            <div>
                <TemperatureInput
                    scale="c"
                    temperature={celsius}
                    onTemperatureChange={this.handleCelsiusChange} />
                <TemperatureInput
                    scale="f"
                    temperature={fahrenheit}
                    onTemperatureChange={this.handleFahrenheitChange} />
                <BoilingVerdict
                    celsius={parseFloat(celsius)} />
            </div>
        );
    }
}
export default App;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值