網龍面試后多久有回應
For the record, asking someone these questions probably isn’t the best way to get a deep understanding of their experience with React. React Interview Questions just seemed like a better title than Things you may or may not need to know in React but you may find helpful none the less.
作為記錄,向某人問這些問題可能不是深入了解其使用React的經驗的最佳方法。 React面試問題似乎比您可能需要或可能不需要在React中知道的事物更好,但您可能會發現有所幫助 。
What happens when you call setState?
調用setState會發生什么?
The first thing React will do when setState is called is merge the object you passed into setState into the current state of the component. This will kick off a process called reconciliation. The end goal of reconciliation is to, in the most efficient way possible, update the UI based on this new state.
調用setState時,React要做的第一件事是將您傳遞給setState的對象合并到組件的當前狀態。 這將啟動稱為對帳的過程。 協調的最終目標是以最有效的方式,根據此新狀態更新UI。
To do this, React will construct a new tree of React elements (which you can think of as an object representation of your UI). Once it has this tree, in order to figure out how the UI should change in response to the new state, React will diff this new tree against the previous element tree.
為此,React將構建一個新的React元素樹(您可以將其視為UI的對象表示)。 一旦擁有了這棵樹,為了弄清楚UI應該如何響應新的狀態而變化,React會將這個新的樹與先前的元素樹進行比較。
By doing this, React will then know the exact changes which occurred, and by knowing exactly what changes occurred, will able to minimize its footprint on the UI by only making updates where absolutely necessary.
通過這樣做,React將隨后知道發生的確切更改,并且確切地知道發生了什么更改,從而僅通過在絕對必要的情況下進行更新,就可以最大程度地減少其在UI上的占用空間。
What’s the difference between an Element and a Component in React?
React中的Element和Component有什么區別?
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.
簡而言之,React元素描述了您想要在屏幕上看到的內容。 簡而言之,React元素是某些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).
React組件是一個函數或類,可以選擇接受輸入并返回React元素(通常通過JSX轉換為createElement
調用)。
For more info, check out React Elements vs React Components
有關更多信息,請查看React Elements與React Components
When would you use a Class Component over a Functional Component?
什么時候在功能組件上使用類 組件 ?
If your component has state or a lifecycle method(s), use a Class component. Otherwise, use a Functional component.
如果您的組件具有狀態或生命周期方法,請使用Class組件。 否則,請使用功能組件。
What are refs in React and why are they important?
React中的ref是什么,為什么如此重要?
Refs are an escape hatch which allow you to get direct access to a DOM element or an instance of a component. In order to use them you add a ref attribute to your component whose value is a callback function which will receive the underlying DOM element or the mounted instance of the component as its first argument.
引用是一個轉義線,可讓您直接訪問DOM元素或組件實例。 為了使用它們,您需要向組件添加ref屬性,該組件的值是一個回調函數,該函數將接收基礎DOM元素或組件的已安裝實例作為其第一個參數。
class UnControlledForm extends Component { handleSubmit = () => { console.log("Input Value: ", this.input.value) } render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' ref={(input) => this.input = input} /> <button type='submit'>Submit</button> </form> ) }}
Above notice that our input field has a ref attribute whose value is a function. That function receives the actual DOM element of input which we then put on the instance in order to have access to it inside of the handleSubmit function.
上面請注意,我們的輸入字段具有ref屬性,其值是一個函數。 該函數接收輸入的實際DOM元素,然后將其放入實例,以便可以在handleSubmit函數內部訪問它。
It’s often misconstrued that you need to use a class component in order to use refs, but refs can also be used with functional components by leveraging closures in JavaScript.
通常會誤解為使用引用需要使用類組件,但是通過利用JavaScript中的閉包,引用也可以與功能組件一起使用。
function CustomForm ({handleSubmit}) { let inputElement return ( <form onSubmit={() => handleSubmit(inputElement.value)}> <input type='text' ref={(input) => inputElement = input} /> <button type='submit'>Submit</button> </form> )}
What are keys in React and why are they important?
React中的鍵是什么,為什么很重要?
Keys are what help React keep track of what items have changed, been added, or been removed from a list.
關鍵是什么,React可以幫助您跟蹤更改,添加或從列表中刪除了哪些項目。
render () { return ( <ul> {this.state.todoItems.map(({task, uid}) => { return <li key={uid}>{task}</li> })} </ul> )}
It’s important that each key be unique among siblings.
重要的是,每個鍵在兄弟姐妹之間必須唯一。
We’ve talked a few times already about reconciliation and part of this reconciliation process is performing a diff of a new element tree with the most previous one.
我們已經討論過幾次對帳了,對帳過程的一部分是將新的元素樹與最近的元素樹進行比較。
Keys make this process more efficient when dealing with lists because React can use the key on a child element to quickly know if an element is new or if it was just moved when comparing trees. And not only do keys make this process more efficient. But without keys, React can’t know which local state corresponds to which item on move. So never neglect keys when mapping.
鍵可以使處理列表時更加高效,因為React可以在子元素上使用鍵來快速知道元素是新元素還是比較樹時是否剛剛移動了元素。 不僅鍵使該過程更有效。 但是沒有鍵,React無法知道哪個本地狀態對應于移動中的哪個項目。 因此,映射時切勿忽略鍵。
If you created a React element like Twitter below, what would the component definition of Twitter look like?
如果你創建了一個陣營元素像下面Twitter的 ,會是什么Twitter的樣子的組件定義?
<Twitter username='tylermcginnis33'> {(user) => user === null ? <Loading /> : <Badge info={user} />}</Twitter>
import React, { Component, PropTypes } from 'react'import fetchUser from 'twitter'// fetchUser take in a username returns a promise// which will resolve with that username's data.
class Twitter extends Component { // finish this}
If you’re not familiar with the render callback pattern, this will look a little strange. In this pattern, a component receives a function as its child.
如果您不熟悉渲染回調模式,這會有些奇怪。 在這種模式下,組件將功能作為其子代。
Take notice of what’s inside the opening and closing <Twitt
er> tags above. Instead of another component as you’ve probably seen before, the Twitter component’s child is a function. What this means is that in the implementation of the Twitter component, we’ll need to treat props.children as a function.
注意上面的<Twitt
er>標簽的開頭和結尾。 T witter組件的子組件是一個函數,而不是您之前可能看到的其他組件。 這意味著在實現T witter組件時,我們需要將props.ch ildren視為一個函數。
Here’s how I went about solving it.
這就是我解決問題的方法。
import React, { Component, PropTypes } from 'react'import fetchUser from 'twitter'
class Twitter extends Component { state = { user: null, } static propTypes = { username: PropTypes.string.isRequired, } componentDidMount () { fetchUser(this.props.username) .then((user) => this.setState({user})) } render () { return this.props.children(this.state.user) }}
Notice that, just as I mentioned above, I treat props.children as a function by invoking it and passing it the user.
注意,正如我上面提到的,我通過調用props.children并將其傳遞給用戶來將其視為一個函數。
What’s great about this pattern is that we’ve decoupled our parent component from our child component. The parent component manages the state and the consumer of the parent component can decide in which way they’d like to apply the arguments they receive from the parent to their UI.
這種模式的優點在于,我們已將父組件與子組件分離。 父組件管理狀態,并且父組件的使用者可以決定以哪種方式將從父接收的參數應用于其UI。
To demonstrate this, let’s say in another file we want to render a Profile instead of a Badge, because we’re using the render callback pattern, we can easily swap around the UI without changing our implementation of the parent (Twitter) component.
為了演示這一點,假設在另一個文件中,我們要呈現一個Profile而不是Badge ,因為我們使用的是render回調模式,因此我們可以輕松地在UI周圍進行交換,而無需更改父( Twitter )組件的實現。
<Twitter username='tylermcginnis33'> {(user) => user === null ? <Loading /> : <Profile info={user} />}</Twitter>
What is the difference between a controlled component and an uncontrolled component?
受控組件和非受控組件有什么區別?
A large part of React is this idea of having components control and manage their own state.
React的很大一部分是讓組件控制和管理自己的狀態的想法。
What happens when we throw native HTML form elements (input, select, textarea, etc) into the mix? Should we have React be the “single source of truth” like we’re used to doing with React? Or should we allow that form data to live in the DOM like we’re used to typically doing with HTML form elements? These questions are at the heart of controlled vs uncontrolled components.
當我們將本地HTML表單元素(輸入,選擇,文本區域等)放入混合中時會發生什么? 我們是否應該像過去使用React一樣使React成為“真理的單一來源”? 還是我們應該像通常使用HTML表單元素那樣允許表單數據存在于DOM中? 這些問題是受控組件與非受控組件的核心。
A controlled component is a component where React is in control and is the single source of truth for the form data. As you can see below, username doesn’t live in the DOM but instead lives in our component state. Whenever we want to update username, we call setState as we’re used to.
受控組件是React在控制之下的組件,并且是表單數據的唯一事實來源。 如下所示, 用戶名不存在于DOM中,而是生活在我們的組件狀態中。 每當我們想要更新username時 ,我們都會像過去那樣調用setState 。
class ControlledForm extends Component { state = { username: '' } updateUsername = (e) => { this.setState({ username: e.target.value, }) } handleSubmit = () => {} render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' value={this.state.username} onChange={this.updateUsername} /> <button type='submit'>Submit</button> </form> ) }}
An uncontrolled component is where your form data is handled by the DOM, instead of inside your React component.
一個不受控制的組件是您的表單數據由DOM處理,而不是在React組件內部。
You use refs to accomplish this.
您可以使用引用來完成此操作。
class UnControlledForm extends Component { handleSubmit = () => { console.log("Input Value: ", this.input.value) } render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' ref={(input) => this.input = input} /> <button type='submit'>Submit</button> </form> ) }}
Though uncontrolled components are typically easier to implement since you just grab the value from the DOM using refs, it’s typically recommended that you favor controlled components over uncontrolled components. The main reasons for this are that controlled components support instant field validation, allow you to conditionally disable/enable buttons, enforce input formats, and are more “the React way”.
盡管不受控制的組件通常更易于實現,因為您只需使用引用從DOM中獲取值,但通常建議您比不受控制的組件更喜歡受控制的組件。 造成這種情況的主要原因是受控組件支持即時字段驗證,允許您有條件地禁用/啟用按鈕,強制輸入格式以及更具“React方式”。
In which lifecycle event do you make AJAX requests and why?
您在哪個生命周期事件中發出AJAX請求,為什么?
AJAX requests should go in the componentDidMount lifecycle event.
AJAX請求應該進入componentDidMount生命周期事件中。
There are a few reasons for this,
這有幾個原因,
Fiber, the next implementation of React’s reconciliation algorithm, will have the ability to start and stop rendering as needed for performance benefits. One of the trade-offs of this is that componentWillMount, the other lifecycle event where it might make sense to make an AJAX request, will be “non-deterministic”. What this means is that React may start calling componentWillMount at various times whenever it feels like it needs to. This would obviously be a bad formula for AJAX requests.
Fiber是React調節算法的下一個實現,將能夠根據需要啟動和停止渲染,以提高性能。 這方面的權衡之一是componentWillMount ,這是另一個可能決定AJAX請求的生命周期事件,將是“不確定的”。 這意味著React可能會在需要時隨時開始調用componentWillMount 。 對于AJAX請求,這顯然是一個不好的公式。
- You can’t guarantee the AJAX request won’t resolve before the component mounts. If it did, that would mean that you’d be trying to setState on an unmounted component, which not only won’t work, but React will yell at you for. Doing AJAX in componentDidMount will guarantee that there’s a component to update. 您不能保證在組件安裝之前AJAX請求不會得到解決。 如果確實如此,那意味著您將嘗試在未安裝的組件上設置setState,這不僅不起作用,而且React也會為您大喊大叫。 在componentDidMount中執行AJAX可以確保存在要更新的組件。
What does shouldComponentUpdate do and why is it important?
ComponentUpdate應該做什么,為什么它很重要?
Above we talked about reconciliation and what React does when setState is called. What shouldComponentUpdate does is it’s a lifecycle method that allows us to opt out of this reconciliation process for certain components (and their child components).
上面我們討論了和解以及調用setState時React的作用。 ComponentUpdate應該做的是一個生命周期方法,使我們可以為某些組件(及其子組件)選擇退出此協調過程。
Why would we ever want to do this?
我們為什么要這樣做?
As mentioned above, “The end goal of reconciliation is to, in the most efficient way possible, update the UI based on new state.” If we know that a certain section of our UI isn’t going to change, there’s no reason to have React go through the trouble of trying to figure out if it should. By returning false from shouldComponentUpdate, React will assume that the current component, and all its child components, will stay the same as they currently are.
如上所述,“對帳的最終目標是以最有效的方式,根據新狀態更新UI。” 如果我們知道UI的某個部分不會改變,那么就沒有理由讓React費勁去嘗試找出是否應該改變。 通過從shouldComponentUpdate返回false,React將假定當前組件及其所有子組件將保持與當前相同。
How do you tell React to build in Production mode and what will that do?
您如何告訴React在生產模式下進行構建,這將做什么?
Typically you’d use Webpack’s DefinePlugin method to set NODE_ENV to production. This will strip out things like propType validation and extra warnings. On top of that, it’s also a good idea to minify your code because React uses Uglify’s dead-code elimination to strip out development only code and comments, which will drastically reduce the size of your bundle.
通常,您將使用Webpack的DefinePlugin方法將NODE_ENV設置為production 。 這將去除諸如propType驗證和額外警告之類的內容。 最重要的是,精簡代碼也是個好主意,因為React使用Uglify的死代碼消除功能來去除僅開發代碼和注釋,這將大大減少程序包的大小。
Why would you use
React.Children.map(props.children, () =>
; ) insteadof props.children.map(() =
> )為什么要使用
React.Children.map(props.children, () =>
;)而不是of props.children.map(() =
>)
It’s not guaranteed that props.children will be an array.
不保證props.children將是一個數組。
Take this code for example:
以下面的代碼為例:
<Parent> <h1>Welcome.</h1></Parent>
Inside of Parent if we were to try to map over children using props.children.map
it would throw an error because props.children
is an object, not an array.
在Parent內部,如果我們嘗試使用props.children.map
映射子props.children.map
,則將拋出錯誤,因為props.children
是一個對象,而不是數組。
React only makes props.children
an array if there are more than one child elements, like this:
如果有多個子元素,React只會使props.children
成為一個數組,如下所示:
<Parent> <h1>Welcome.</h1> <h2>props.children will now be an array</h2></Parent>
This is why you want to favor React.Children.map
because its implementation takes into account that props.children may be an array or an object.
這就是為什么要支持React.Children.map
原因,因為它的實現考慮到props.children可以是數組或對象。
Describe how events are handled in React.
描述如何在React中處理事件。
In order to solve cross browser compatibility issues, your event handlers in React will be passed instances of SyntheticEvent, which is React’s cross-browser wrapper around the browser’s native event. These synthetic events have the same interface as native events you’re used to, except they work identically across all browsers.
為了解決跨瀏覽器兼容性問題,React中的事件處理程序將傳遞SyntheticEvent實例,該實例是React跨瀏覽器本機事件的跨瀏覽器包裝器。 這些合成事件與您慣用的本機事件具有相同的界面,除了它們在所有瀏覽器中的工作方式相同。
What’s mildly interesting is that React doesn’t actually attach events to the child nodes themselves. React will listen to all events at the top level using a single event listener. This is good for performance and it also means that React doesn’t need to worry about keeping track of event listeners when updating the DOM.
有點有趣的是,React實際上并未將事件附加到子節點本身。 React將使用單個事件偵聽器在頂層偵聽所有事件。 這對性能有好處,也意味著React在更新DOM時無需擔心跟蹤事件監聽器。
What is the difference between createElement and cloneElement?
createElement和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. They nailed the naming on these two ?.
createElement是JSX編譯到的對象,也是React用于創建React Elements(某些UI的對象表示)的對象。 cloneElement用于克隆元素并將新的道具傳遞給它。 他們將這兩個命名命名為?。
What is the second argument that can optionally be passed to setState and what is its purpose?
可以有選擇地傳遞給setState的第二個參數是什么,其目的是什么?
A callback function which will be invoked when setState has finished and the component is re-rendered.
setState完成并重新呈現組件后將調用的回調函數。
Something that’s not spoken of a lot is that setState is asynchronous, which is why it takes in a second callback function. Typically it’s best to use another lifecycle method rather than relying on this callback function, but it’s good to know it exists.
沒多說的是setState是異步的,這就是為什么它需要第二個回調函數的原因。 通常,最好是使用其他生命周期方法,而不要依賴此回調函數,但是很高興知道它的存在。
this.setState( { username: 'tylermcginnis33' }, () => console.log('setState has finished and the component has re-rendered.'))
What is wrong with this code?
此代碼有什么問題?
this.setState((prevState, props) => { return { streak: prevState.streak + props.count }})
Nothing is wrong with it ?. It’s rarely used and not well known, but you can also pass a function to setState that receives the previous state and props and returns a new state, just as we’re doing above. And not only is nothing wrong with it, but it’s also actively recommended if you’re setting state based on previous state.
沒有錯嗎? 它很少使用并且不為人所知,但是您也可以像上面所做的那樣 ,將一個函數傳遞給s etState來接收先前的狀態和props并返回一個新的狀態。 不僅沒有錯,而且如果您要基于先前的狀態來設置狀態,也積極建議使用。
Follow Tyler McGinnis on Twitter ??Originally published at tylermcginnis.com.
在Twitter上關注Tyler McGinnis?? 最初發布于tylermcginnis.com 。
翻譯自: https://www.freecodecamp.org/news/react-interview-questions-c8a319ed02bd/
網龍面試后多久有回應