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

作者: 张中华 | 来源:发表于2018-11-14 23:54 被阅读44次

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


开始呢,我们先创建一个名为 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() 方法:



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;

相关文章

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

    使用 react 经常会遇到几个组件需要共用状态数据的情况。这种情况下,我们最好将这部分共享的状态提升至他们最近的...

  • React

    React 《React 官网文档》 React简介 React概念 React官网学习实践 - jSX简介 Re...

  • react状态提升

    状态提升 官网摄氏度与华氏度转化的例子 // class BoilingVerdict extends React...

  • React HOC

    在React官网文档学习React HOC,整个看了一遍还是云里雾里的,于是按照官网文档,自己动手实践一下。官网地...

  • React官网学习实践 - React安装

    创建一个新的APP 2.如果您安装了npm 5.2.0以以上版本的话,您可以使用npx作为一个更好的选择。 安装 ...

  • React官网学习实践 - 表单

    HTML表单元素与React中的其他DOM元素有所不同,因为表单元素生来就保留一些内部状态。例如,下面这个表单只接...

  • React Native 资源

    学习资源 文档 知识图谱 React Native 官网(英文) React Native 中文网 React N...

  • React学习笔记.md

    React官网学习笔记 扩展 Pete Hunt: React: Rethinking best practice...

  • React 进阶二 组件详解

    React组件 React的组件大概分为俩部分,无状态组件和有状态组件 无状态组件。下面React官网中定义的一个...

  • React学习资源汇总

    React学习资源汇总 React 官方 官网地址:http://facebook.github.io/react...

网友评论

    本文标题:React官网学习实践 - 状态提升

    本文链接:https://www.haomeiwen.com/subject/mtnsfqtx.html