@wanqiuz 2018-04-27 11:54:34发表于 wanqiuz/blog-articles React集锦

1 Class Component or Functional Component

如果一个component有state或者lifecycle method,用class component,否则用Functional Component。

2 在哪个lifecycle method进行AJAX请求

AJAX 请求应该在 componentDidMount 生命周期事件中。 有两个原因:
(1) Fiber,是React v16实施的新的和解算法,将有能力根据需要启动和停止渲染,以获得性能优势。其中一个取舍之一是 componentWillMount 。 React 可以在不同的时间调用 componentWillMount很多次,这个生命周期随时可能被打断。(进入到render周期就不会被打断了)这显然是AJAX请求的不好的方式。
(2) 不能保证在组件挂载之前,AJAX请求将无法 resolve。如果AJAX请求在组件挂载之前resolve了,那意味着会在一个未挂载的组件上 SetState,参考React生命周期,它会进入到shouldComponentUpdate中,此时会报错。 在 componentDidMount 中执行 AJAX 将保证组件会被更新。

3 What’s the difference between an Element and a Component in React?

Simply put, a React element describes what you want to see on the screen. Not so simply put, a React element is an object representation of some UI.

A React component is a function or a class which optionally accepts input and returns a React element (typically via JSX which gets transpiled to a createElement invocation).

4 Why would you use, () => ) instead of => )

It’s not guaranteed that props.children will be an array.

Take this code for example,


Inside of Parent if we were to try to map over children using it would throw an error because props.children is an object, not an array.

React only makes props.children an array if there are more than one child elements, like this

  <h2>props.children will now be an array</h2>

This is why you want to favor because its implemention takes into account that props.children may be an array or an object.

5 What is the difference between createElement and cloneElement?

createElement is what JSX gets transpiled to and is what React uses to create React Elements (object representations of some UI). cloneElement is used in order to clone an element and pass it new props.