React State&生命周期

State&生命周期

State&生命周期

到目前为止我们只学习了一种方法来更新UI。

我们调用ReactDOM.render()来改变输出:

function tick(){
    const element = (
        <div>
            <h1>Hello,world!</h1>
            <h2>It is {new Date().toLocaleTimeString()}</h2>
        </div>
    )
};

ReactDOM.render(
    element,
    document.getElementById('root')
);

setInterval(tick,1000);
//每秒调用一次tick,tick每秒执行一次ReactDOM.render()方法来更新视图。

本节封装Clock组件,组件将会设置自己的定时器,并每秒更新一次。

从封装时钟开始:

//封装Clock组件
function Clock(props){
    return (
        <div>
            <h1>Hello,world!</h1>
            <h2>It is {props.date.toLocaleTimeString()}</h2>
        </div>
    )
}

//将组件在tick函数中使用

function tick(){
ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
);

setInterval(tick,1000);

然而它错过了一个关键的要求:Clock设置一个定时器并且每秒更新UI应该是Clock的实现细节。

理想情况下,我们写一次Clock然后它能更新自身:

ReactDOM.render(
    <Clock />,
    document.getElementById('root')
)

为了实现这个需求,,我么需要为Clock,组件添加状态

状态与属性十分相似,但状态是私有的,完全受控于当前组件。

之前提到过,定义为类的组件有一些特性。局部状态就是如此:一个功能只适用于类。

将函数转换为类

可以通过五个步骤将函数组件Clock转换为类

  1. 创建一个名称扩展为React.ComponentES6类

  2. 创建一个叫做render()的控方法

  3. 将函数体移动到render()方法中

  4. render()方法中,使用this.props替换props

  5. 删除剩余的空函数声明

class Clock extends  React.Component{
    render(
        return (
            <div>
            <h1>Hello,world!</h1>
            <h2>It is {this.props.date.toLocaleTimeString()}</h2>
        </div>
        )
    )
}

Clock现在被定义为一个类而不是一个函数

使用类就允许我们使用其他特性,例如局部状态,生命周期钩子。

为一个类添加局部状态

我们会通过3个步骤将date属性移动到状态中:

  1. render()方法中使用this.state.date替代this.props.date
class Clock extends  React.Component{
    render(
        return (
            <div>
            <h1>Hello,world!</h1>
            <h2>It is {this.state.date.toLocaleTimeString()}</h2>
        </div>
        )
    )
}
  1. 添加一个类构造函数来初始化状态this.state
class Clock extends  React.Component{
    
    constructor(props){
        super(props);
        this.state={date:new Date()}
    }
    render(
        return (
            <div>
            <h1>Hello,world!</h1>
            <h2>It is {this.state.date.toLocaleTimeString()}</h2>
        </div>
        )
    )
}

注意如何桩底props到基础构造函数的:

constructor(props){
    super(props);
    this.state={date:new Date()}
}

类组件应始终使用props条用基础构造函数。

  1. <Clock />元素移出data属性:
ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

稍后将定时器代码添加回组件本身。

结果如下:

class Clock extends  React.Component{
    constructor(props){
        super(props);
        this.state={date:new Date()}
    }
    render(
        return (
            <div>
            <h1>Hello,world!</h1>
            <h2>It is {this.state.date.toLocaleTimeString()}</h2>
        </div>
        )
    )
    ReactDOM.render(
      <Clock />,
      document.getElementById('root')
    );
}

接下来给Clock设置自己的计时器,并每秒更新一次。

将生命周期方法添加到类中

在具有许多组件的应用程序中,在销毁时释放组件所占用的资源非常重要。

每当Clock组件第一次加载到DOM中的时候,我们生成定时器这在React中被称为挂载

同样,每当Clock生成的这个DOM被移除的时候,我们也要清除定时器,这在React中被称为卸载

我们可以再组件类上声明特殊的方法,当组件挂载或卸载时,来运行一些代码:

class Clock extends  React.Component{
    constructor(props){
        super(props);
        this.state={date:new Date()}
    }
    componentDidMount(){
        
    }
    componentWillUnmount(){
        
    }
    render(
        return (
            <div>
            <h1>Hello,world!</h1>
            <h2>It is {this.state.date.toLocaleTimeString()}</h2>
        </div>
        )
    )
    ReactDOM.render(
      <Clock />,
      document.getElementById('root')
    );
}

这些方法被称为生命周期钩子函数

当组件输出到DOM后会执行componentDidMount()钩子,我们在这里建立定时器:

componentDidMount(){
    this.timerID = setInterval(()=>{
        this.tick()
    },1000)
}

注意我们如何在this中白村定时器ID。

虽然this.props由React本身设置以及this.state具有特殊含义,但如果需要存储不用于视觉输出的东西,则可以手动向类中添加其他字段。

如果你不在render()中使用某些东西,它就不应该在状态中。

我们将在componentWillUnmount()生命周期钩子中卸载定时器:

componentWillUnmount(){
    clearInterval(this.timerID);
}

最后我们实现了每秒中执行tick()的方法。

它将使用this.setState()来更新组件局部状态:

class Clock extends  React.Component{
    constructor(props){
        super(props);
        this.state={date:new Date()}
    }
    componentDidMount(){
        
    }
    componentWillUnmount(){
        
    }
    tick(){
        this.setState({
            date:new Date();
        })
    }
    render(
        return (
            <div>
            <h1>Hello,world!</h1>
            <h2>It is {this.state.date.toLocaleTimeString()}</h2>
        </div>
        )
    )
    ReactDOM.render(
      <Clock />,
      document.getElementById('root')
    );
}

现在时钟每秒都会执行。

让我们快速回顾一下发生了什么以及条用方法的顺序:

  1. <Clock />被传递给ReactDOM.render()时,React条用Clock组件的构造函数。由于Clock需要显示当前时间,所以使用包含当前时间的对象来初始化this.state。我们稍后会更新此状态。

  2. React然后调用Clock组件的render()方法。这是React了解屏幕上应该显示什么内容,然后React更新DOM以匹配Clock的渲染输出。

  3. Clock的输出插入到DOM中时,React调用componentDidMount()生命周期钩子。再起中,Clock组件要求浏览器设置一个定时器,每秒钟调用一次tick().

  4. 浏览器每秒中调用tick()方法。在其中,Clock组件通过使用包含当前时间的对象调用setState(),来调度UI更新。通过调用setState(),React知道状态已经改变,并在此调用render(),方法来确定屏幕上应当显示什么。这一次,render()方法中的this.state.date将不同,所以渲染输出将包含更新的时间,并相应地更新DOM。

  5. 一旦Clock组件被从DOM中移除,React将会条用componentWillUnmount()这个钩子函数,并清除定时器。

正确的使用状态

关于this.setState()有三个地方需要知道

不要直接更新状态

例如,此代码不会重新渲染组件:

//Wrong

this.state.comment='hello';

应当使用this.setState():

//Correct

this.setState({comment:'hello'});

构造函数是唯一能够初始化this.state的地方。

状态更新可能是异步的

React可以将多个setState()调用和并成一个调用来提高性能。

因为this.propsthis.state可能是异步更新的,你不应该依靠它们的值来计算下一个状态。

例如,此代码可能无法更新计数器:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

要修复它,请使用第二种形式的setState()来接受一个函数而不是一个对象。该函数将接收先前的状态作为第一个参数,将此次更新被应用时的props作为第二个参数:

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

上方代码使用了箭头函数,但它也适用于常规函数:

// Correct
this.setState(function(prevState, props) {
  return {
    counter: prevState.counter + props.increment
  };
});

状态更新合并

当你调用 setState() 时,React 将你提供的对象合并到当前状态。

例如,你的状态可能包含一些独立的变量:

 constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: []
    };
  }

你可以调用 setState() 独立地更新它们:

componentDidMount() {
    fetchPosts().then(response => {
      this.setState({
        posts: response.posts
      });
    });

    fetchComments().then(response => {
      this.setState({
        comments: response.comments
      });
    });
  }

这里的合并是浅合并,也就是说this.setState({comments})完整保留了this.state.posts,但完全替换了this.state.comments

数据自顶向下流动

父组件或子组件都不能知道某个组件是有状态还是无状态,并且它们不应该关心某组件是被定义为一个函数还是一个类。

这就是为什么状态通常被称为局部或封装。 除了拥有并设置它的组件外,其它组件不可访问。

组件可以选择将其状态作为属性传递给其子组件:

<h2>It is {this.state.date.toLocaleTimeString()}.</h2>

这也适用于用户定义的组件:

<FormattedDate date={this.state.date} />

FormattedDate 组件将在其属性中接收到 date 值,并且不知道它是来自 Clock 状态、还是来自 Clock 的属性、亦或手工输入:

function FormattedDate(props) {
  return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}

这通常被称为自顶向下单向数据流。 任何状态始终由某些特定组件所有,并且从该状态导出的任何数据或 UI 只能影响树中下方的组件。

如果你想象一个组件树作为属性的瀑布,每个组件的状态就像一个额外的水源,它连接在一个任意点,但也流下来。

为了表明所有组件都是真正隔离的,我们可以创建一个 App 组件,它渲染三个Clock

function App() {
  return (
    <div>
      <Clock />
      <Clock />
      <Clock />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

每个 Clock 建立自己的定时器并且独立更新。

在 React 应用程序中,组件是有状态还是无状态被认为是可能随时间而变化的组件的实现细节。 可以在有状态组件中使用无状态组件,反之亦然。

只研朱墨作春山
原文地址:https://www.cnblogs.com/guolintao/p/9003054.html