zoukankan      html  css  js  c++  java
  • 深入浅出React的一些细节——State

    (来源于: https://facebook.github.io/react/docs/state-and-lifecycle.html 翻译by:@TimRChen)

    Using State Correctly

    There are three things you should know about setState().

    1.Do Not Modify State Directly

    For example, this will not re-render a component:

    // Wrong
    this.state.comment = 'Hello';
    

    Instead, use setState():

    // Correct
    this.setState({comment: 'Hello'});
    

    The only place where you can assign this.state is the constructor.

    2.State Updates May Be Asynchronous

    React may batch multiple setState() calls into a single update for performance.

    Because this.props and this.state may be updated asynchronously(异步的), you should not rely on their values for calculating the next state你不应该依赖它们计算的值传递给下一个状态).

    For example, this code may fail to update the counter:

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

    To fix it, use a second form of setState() that accepts a function rather than an object接受一个回调函数而不是一个对象). That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

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

    We used an arrow functionES6箭头函数) above, but it also works with regular functions:

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

    The Data Flows Down

    Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn't care whether it is defined as a function or a class.

    This is why state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it. 除了组件本身,其他组件无法调用该组件的state

    A component may choose to pass its state down as props to its child components: (一个组件可以选择将它的state作为props传递给它的子组件

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

    This also works for user-defined(自定义 components:

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

    The FormattedDate component would receive the date in its props and wouldn't know whether it came from the Clock's state, from the Clock's props, or was typed by handFormattedDate组件会在它的props中获得date,并且不会知道date来自Clock组件的state,还是来自Clock组件的props,或是手动输入的):

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

    Try it on CodePen.<——代码链接

    This is commonly called a "top-down" or "unidirectional" data flow单向数据流). Any state is always owned by some specific component, and any data or UI derived from that state can only affect components "below" them in the tree.任何state都属于具体的组件,任何来自与该state的数据或者UI都只能影响低于该state所在组件下的子组件——>也就是说当前state所在组件默认为父组件

    If you imagine a component tree as a waterfall of props, each component's state is like an additional water source that joins it at an arbitrary point but also flows down.假如将组件树作为props瀑布,每个组件的state就好比加入到整个props瀑布中作为一个任意点的水源,而不是水流

    To show that all components are truly isolated相互独立), we can create an App component that renders three <Clock>s:

    function App() {
      return (
        <div>
          <Clock />
          <Clock />
          <Clock />
        </div>
      );
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById('root')
    );
    

    Try it on CodePen. (<——代码链接

    Each Clock sets up its own timer and updates independently.(每一个Clock组件建立它们自己的定时器并且互不干扰地进行更新

    In React apps, whether a component is stateful or stateless is considered an implementation detail of the component that may change over time. You can use stateless components inside stateful components, and vice versa.你可以使用无状态的组件在充满了状态的组件中,反之亦然

    总结:今天深入浅出的总结了下关于React中的state使用中的一些细节,以及state与props之间的一些牵连。

    ps: 转载请注明出处。@TimRChen

  • 相关阅读:
    学习Ember遇到的一些问题
    angular学习资源
    电话号码验证(正则)
    使用 Bitbucket Pipelines 持续交付托管项目
    zookeepercli
    如何用 JIRA REST API 创建 Issue
    Maven如何传递系统属性变量到TestNG
    基于WebDriver&TestNG 实现自己的Annotation @TakeScreenshotOnFailure
    25+ Useful Selenium Web driver Code Snippets For GUI Testing Automation
    Selenium WebDriver 之 PageObjects 模式 by Example
  • 原文地址:https://www.cnblogs.com/tim100/p/6792149.html
Copyright © 2011-2022 走看看