This is the 13th day of my participation in Gwen Challenge

Hi, I’m @Luo Zhu, a blogger who keeps writing. Thank you for every like and comment you make.

This article was first published on luo Zhu’s official website

Translated from Sudheerj/reactJs-interlocution-Questions

This article synchronizes in the public account Luo Zhu early teahouse, reprint please contact the author.

1. How to use styles in React?

The style property accepts a JavaScript object with a small camel name property, rather than a CSS string. This is consistent with DOM style JavaScript attributes, is more efficient, and protects against XSS security vulnerabilities.

const divStyle = {
  color: 'blue'.backgroundImage: `url(${imgUrl}) `};function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!</div>;
}
Copy the code

Style is in conformity with the hump nomenclature, keys to access in the JavaScript DOM node attributes are consistent (such as node. Style. The backgroundImage).

2. How are events different in React?

Handling events in React elements has some syntactic differences:

There are some syntactic differences in handling events on the React element:

  1. React event handlers use small camel names instead of lowercase.
  2. With JSX, you pass a function as an event handler, not a string.

3. If you use it in a constructorsetState()What happens?

When you use setState(), React also re-renders the component and all its children in addition to the state assigned to the object. You get the error that only one mounted or mounting component can be updated. So we need to use this.state to initialize variables in the constructor.

4. What are the effects of indexes as keys?

Keys should be stable, predictable, and unique so React can track elements.

In the code snippet below, the keys for each element are indexed rather than associated with the data being represented. This limits the optimizations that React can make.

{
  todos.map((todo, index) = > <Todo {. todo} key={index} />);
}
Copy the code

If you use element data as a unique key, assuming that todo.id is unique and stable in this list, React will be able to reorder elements without having to recalculate them as before.

{
  todos.map(todo= > <Todo {. todo} key={todo.id} />);
}
Copy the code

In 5.componentWillMount()Method.setStateReally?

Yes, it is safe to use setState() in the componentWillMount() method. At the same time, however, it is recommended to avoid asynchronous initialization in the componentWillMount() lifecycle method. ComponentWillMount () is called immediately before the mount occurs. It is called before render(), so setting state in this method does not trigger rerendering. Avoid introducing any side effects or subscriptions into this method. We need to make sure that the asynchronous call to component initialization occurs at componentDidMount() and not At componentWillMount().

componentDidMount() {
  axios.get(`api/todos`).then((result) = > {
    this.setState({
      messages: [...result.data]
    })
  })
}
Copy the code

6. What happens if you use props in the initial state?

If the props on the component is changed and the component is not refreshed, the new props value will never be displayed because the constructor never updates the current state of the component. State initialization from props is run only when the component is first created.

The following component will not display the updated input value.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      records: [].inputValue: this.props.inputValue,
    };
  }

  render() {
    return <div>{this.state.inputValue}</div>; }}Copy the code

Using props in the Render method updates the values.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      record: [],}; }render() {
    return <div>{this.props.inputValue}</div>; }}Copy the code

7. How do you conditionally render components?

In some cases, you want to render different components based on some state. JSX does not render false or undefined, so you can use conditional shorting to render a part of your component only if a condition is true.

const MyComponent = ({ name, address }) = > (
  <div>
    <h2>{name}</h2>
    {address && <p>{address}</p>}
  </div>
);
Copy the code

If you need an if-else condition, use the ternary operator.

const MyComponent = ({ name, address }) = > (
  <div>
    <h2>{name}</h2>
    {address ? <p>{address}</p> : <p>{'Address is not available'}</p>}
  </div>
);
Copy the code

8. Why should we be careful passing props on DOM elements?

When we pass props, we run the risk of adding unknown HTML attributes, which is a bad practice. Instead, we can use something with… The prop deconstruction of the REST operator, so it will only add the required prop.

For example.

const ComponentA = () = > (
  <ComponentB isDisplay={true} className={'componentStyle'} / >
);

const ComponentB = ({ isDisplay, ... domProps }) = > (
  <div {. domProps} >{'ComponentB'}</div>
);
Copy the code

9. How to use decorators in React?

You can decorate your class components the same way you pass a component into a function. Decorators are a flexible and readable way to modify component functionality.

@setTitle('Profile')
class Profile extends React.Component {
  //....
}

/* title is a string that will be set to the document title. WrappedComponent is what our decorator will receive when placed directly on a component class, as shown in the example above */
const setTitle = title= > WrappedComponent= > {
  return class extends React.Component {
    componentDidMount() {
      document.title = title;
    }

    render() {
      return <WrappedComponent {. this.props} / >; }}; };Copy the code

Note: Decorator is a feature that does not make it into ES7, but is currently a phase 2 proposal.

10. How to memo a component?

There are several cache libraries available for functional components.

For example, the Moize library can memo a component in another component.

import moize from 'moize';
import Component from './components/Component'; // This module exports a non-MEMO component

const MemoizedFoo = moize.react(Component);

const Consumer = () = > {
  <div>
    {'I will memoize the following entry:'}
    <MemoizedFoo />
  </div>;
};
Copy the code

Update: As of React V16.6.0, we have a React. Memo. It provides a higher-order component that is cached unless the props changes. To use it, simply wrap the component in React. Memo before using it.

const MemoComponent = React.memo(function MemoComponent(props) {
  /* render using props */
});
/ / or
export default React.memo(MyFunctionComponent);
Copy the code