Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React16新特性(更新日志及文档翻译) #10

Open
Yolo-0317 opened this issue May 15, 2019 · 0 comments
Open

React16新特性(更新日志及文档翻译) #10

Yolo-0317 opened this issue May 15, 2019 · 0 comments

Comments

@Yolo-0317
Copy link
Owner

Yolo-0317 commented May 15, 2019

React16新特性(更新日志翻译)

声明: 从精读《React16 新特性》引用了部分翻译

更新日志原文地址__点击

16.0.0 (2017/9/26)

New JS Environment Requirements(需要新的js运行环境)

React 16 depends on the collection types Map and Set, as well as requestAnimationFrame. If you support older browsers and devices which may not yet provide these natively (e.g. < IE11), you may want to include a polyfill.

React16依赖于Map和Set这两种集合类型(ES6新增),以及requestAnimationFrame。如果项目需要支持旧版本的浏览器和设备(例如版本低于IE11),那么需要引入polyfill。

New Features(新特性)
  1. Components can now return arrays and strings from render. (Docs coming soon!)

组件可以直接在render方法中返回数组和字符串

// 不需要再将数组雷元素使用父元素进行包裹,减少dom节点嵌套
render() {
  return [
    <li/>1</li>,
    <li/>2</li>,
    <li/>3</li>,
  ];
}
  1. Improved error handling with introduction of "error boundaries". Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

通过引入“error bounaries”优化错误处理。Error boundaries是用来捕获子组件树中任意位置错误的React组件,记录错误并返回fallbackUI(从下面代码中理解该UI),而不是导致组件树崩溃。

引申官网介绍:React15 在渲染过程中遇到运行时的错误,会导致整个 React 组件的崩溃,而且错误信息不明确可读性差。React16 支持了更优雅的错误处理策略,如果一个错误是在组件的渲染或者生命周期方法中被抛出,整个组件结构就会从根节点中卸载,而不影响其他组件的渲染,可以利用 error boundaries 进行错误的优化处理。

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
  1. First-class support for declaratively rendering a subtree into another DOM node with ReactDOM.createPortal(). (Docs coming soon!)

使用ReactDOM.createPortal()对使用声明式渲染将一个子树添加到另一个DOM节点中的做法提供支持

codepen: Example: Portal event bubbling

codepen中的例子表明,通过将createPortal创建的Modal组件作为Parent子组件,这样Modal中的click事件会冒泡到Parent中被捕获。

  1. Streaming mode for server side rendering is enabled with ReactDOMServer.renderToNodeStream() and ReactDOMServer.renderToStaticNodeStream()

通过ReactDOMServer.renderToNodeStream()和ReactDOMServer.renderToStaticNodeStream支持服务器端渲染的流模式

  1. React DOM now allows passing non-standard attributes.

React DOM允许设置非标准的dom属性

// Your code:
<div mycustomattribute="something" />

// React 15 output:
<div />

// React 16 output:
<div mycustomattribute="something" />

但是对于已知的属性,仍然应该使用规范的React命名方式
tabIndex解释

// Yes, please
<div tabIndex="-1" />

// Warning: Invalid DOM property `tabindex`. Did you mean `tabIndex`?
<div tabindex="-1" />
Breaking Changes(突破性改变)
1. There are several changes to the behavior of scheduling and lifecycle methods:

调用方式和声明周期有几处变化:

  • ReactDOM.render() and ReactDOM.unstable_renderIntoContainer() now return null if called from inside a lifecycle method.

如果在生命周期方法内部调用ReactDOM.render()和ReactDOM.unstable_renderIntoContainer()会返回null。

  1. To work around this, you can either use the new portal API or refs.
  1. 要解决这个问题,可以使用新的portalAPIrefs
  • Minor changes to setState behavior:

对setState行为进行小的改变

  1. Calling setState with null no longer triggers an update. This allows you to decide in an updater function if you want to re-render.

使用null调用setState不再触发更新。 这允许您在更新方法中决定是否要重新渲染。

  1. Calling setState directly in render always causes an update. This was not previously the case. Regardless, you should not be calling setState from render.

直接在render中调用setState总是会导致更新。 以前不是这种情况。 无论如何,不应该在render方法中调用setState。

  1. setState callback (second argument) now fires immediately after componentDidMount / componentDidUpdate instead of after all components have rendered.

setState的回调函数(第二个参数)现在会在componentDidMount / componentDidUpdate之后立即触发,而不是在所有组件都已渲染之后触发。

  • When replacing with , B.componentWillMount now always happens before A.componentWillUnmount. Previously, A.componentWillUnmount could fire first in some cases.

当用组件B替换组件A时,B组件的componentWillMount 总是在A组件的componentWillUnmount之前触发。在以往的版本中A组件的componentWillUnmount可能会优先触发

  • Previously, changing the ref to a component would always detach the ref before that component's render is called. Now, we change the ref later, when applying the changes to the DOM.

未理解。。。。

  • It is not safe to re-render into a container that was modified by something other than React. This worked previously in some cases but was never supported. We now emit a warning in this case. Instead you should clean up your component trees using ReactDOM.unmountComponentAtNode. See this example.

将组件重新渲染到一个被其他库修改的容器的做法是不安全的。在旧版本中这样的做法时可行的但并不提倡。现在会对这种情况发出警告。应该使用ReactDOM.unmountComponentAtNode来清理组件树。例子代码如下:

// not support
ReactDOM.render(<App />, div);
div.innerHTML = 'nope';
ReactDOM.render(<App />, div); // Rendering into something that's not been properly cleaned up

// fixed code
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
div.innerHTML = 'nope';
ReactDOM.render(<App />, div); // Now it's okay
  • componentDidUpdate lifecycle no longer receives prevContext param.

componentDidUpdate生命周期不再接收prevContext参数。 #8631

  • Non-unique keys may now cause children to be duplicated and/or omitted. Using non-unique keys is not (and has never been) supported, but previously it was a hard error.

非唯一键现在可能导致子组件被复制或省略。 使用非唯一键是从来都不允许的,但以前的版本中这是一个硬性的错误。但是简单的对比并没有发现什么区别呢。。。

  • Shallow renderer no longer calls componentDidUpdate() because DOM refs are not available. This also makes it consistent with componentDidMount() (which does not get called in previous versions either).
  • Shallow renderer does not implement unstable_batchedUpdates() anymore.
  • ReactDOM.unstable_batchedUpdates now only takes one extra argument after the callback.
2. The names and paths to the single-file browser builds have changed to emphasize the difference between development and production builds. For example:

单个文件的浏览器版本的名称和路径已更改,以强调开发和生产版本之间的差异。 例如:

react/dist/react.js → react/umd/react.development.js
react/dist/react.min.js → react/umd/react.production.min.js
react-dom/dist/react-dom.js → react-dom/umd/react-dom.development.js
react-dom/dist/react-dom.min.js → react-dom/umd/react-dom.production.min.js

3. The server renderer has been completely rewritten, with some improvements:

对服务器渲染进行重写并改进

  • Server rendering does not use markup validation anymore, and instead tries its best to attach to existing DOM, warning about inconsistencies. It also doesn't use comments for empty components and data-reactid attributes on each node anymore.
  • Hydrating a server rendered container now has an explicit API. Use ReactDOM.hydrate instead of ReactDOM.render if you're reviving server rendered HTML. Keep using ReactDOM.render if you're just doing client-side rendering.
Removed Deprecations 删除弃用
1. There is no react-with-addons.js build anymore. All compatible addons are published separately on npm, and have single-file browser versions if you need them.

不再使用react-with-addons.js构建任何东西,所有的兼容插件都在npm上有单独发布的包,如果需要也可以引入浏览器版本的单个文件

  • The deprecations introduced in 15.x have been removed from the core package. React.createClass is now available as create-react-class, React.PropTypes as prop-types, React.DOM as react-dom-factories, react-addons-test-utils as react-dom/test-utils, and shallow renderer as react-test-renderer/shallow. See 15.5.0 and 15.6.0 blog posts for instructions on migrating code and automated codemods.

在15.x版本中介绍的弃用都已经在核心包中移除。React.createClass用create-react-class包替代l,React.PropTypes使用prop-types。React.DOM使用react-dom-factories。react-addons-test-utils使用react-dom/test-utils。shallow renderer使用react-test-renderer/shallow。 有关迁移代码和自动代码模块的说明,请参阅15.5.015.6.0博客文章。

16.1.0 2017/11/9)

Discontinuing Bower Releases(停止Bower上的发布)

Starting with 16.1.0, we will no longer be publishing new releases on Bower. You can continue using Bower for old releases, or point your Bower configs to the React UMD builds hosted on unpkg that mirror npm releases and will continue to be updated.

从16.1.0版本开始,我们将不再在Bower上发布新版本。 您可以继续使用Bower获取旧版本,或者将Bower配置指向在镜像npm版本的unpkg上托管的React UMD版本,并将继续更新。

React
  • Add support for portals in React.Children utilities.

React.Children中添加对portals的支持

React.Children的方法

  • React.Children.map
  • React.Children.forEach
  • React.Children.count
  • React.Children.only(验证children只有一个子项(必须是React元素)并返回这个React元素。 否则此方法会引发错误(==React.Children.only expected to receive a single React element child.==))
  • React.Children.toArray(将传入的children中的子节点处理成一个数组)
// If children is null or undefined, this method will return null or undefined rather than an array.

children: [1, null]
React.Children.map(children, function[(thisArg)]); // ['1']
React.Children.count(children); //2
React.Children.only(children)

// children: <div/><div/>1
React.Children.toArray(children); // [divObj, divObj, "1"]

16.2.0 (2017/9/28)

React
  • Add Fragment as named export to React

可以从react中直接到处的增加Fragment标签命名

import { Fragment } from 'react'; 

16.8.0 (2019/2/6)

  • Add Hooks — a way to use state and other React features without writing a class

添加Hooks - 一种允许不构建class而使用stat和其他react特性的方式

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

16.3.0 (2018/3/29)

React
  • Add a new officially supported context API.

官方支持context API

1.什么时候使用Context

Context旨在共享可被视为React组件树的“全局”的数据,例如当前经过身份验证的用户,主题或首选语言。

相关API:

  • React.createContext
  • Context.Provider
  • Class.contextType
  • Context.Consumer
const ThemeContext = React.createContext('light');
  • Add a new React.createRef() API as an ergonomic alternative to callback refs.

添加新API--React.createRef()作为refs的回调

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }
  
  render() {
    return <input type="text" ref={this.inputRef} />;
  }

  componentDidMount() {
    this.inputRef.current.focus();
  }
}
  • Add a new React.forwardRef() API to let components forward their refs to a child.

添加新的API-React.forwardRef()允许组件将它的refs传递给子组件

通过传递ref可以获取子组件的DOM节点

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
@Yolo-0317 Yolo-0317 changed the title React16新特性(更新日志翻译) React16新特性(更新日志及文档翻译) May 16, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant