Study notes-react finely divided knowledge points


The following are some fragments and discontinuous knowledge points encountered during the learning process of react. For example: similar to the template tag in vue, similar to how "computed attributes" in vue is implemented.

1. Similar to how the template tag in vue is implemented:

In React, there can only be one root node in the return of the component, the required node is already in the parent component, and the child component does not want to add extra labels. At this time, a label is needed. When the child component is rendered to the parent component, it is equivalent to not having it. There are two ways to achieve this:

// 使用空标签包裹子组件
<>
    <div></div>
    <span></span>
</>

// 使用Fragment标签
import React, { Fragment } from 'react';
<Fragment>
    <div></div>
    <span></span>
</Fragment>

2. Similar to "computed properties" in vue:

The nature of the calculated attribute: when a function is called, if the provided parameters are the same as the last call, the function will not be executed, and the last result will be returned directly, thus reducing the call of the function.

To implement similar functions in React, you need a package: memoize-one to cache the function results. Download in the project command window.

yarn add memoize-one

Note when using: The data required by the function needs to be passed to the function after used formal parameters.

import memoize from 'memoize-one';

findAvatar = memoize(activeId => {
    let target   = this.state.listMain.find(item => item.id === activeId);
    return target ? "http://localhost:3000" + target.avatar : "";
});

render() {
    let contextValue = {
        ...this.state,
        changeCategory: this.changeCategory,
        avatar: this.findAvatar(this.state.activeId)
    };
    return (
       <Context.Provider value={ contextValue }>
           <UICategory />
       </Context.Provider>
    );
}

3. Similar to watch event monitoring in vue:

There is no direct event monitoring in React, and watch event monitoring can be implemented indirectly through the componentDidUpdate function.

The essence of event monitoring is: if a piece of data changes, a series of operations will occur.

In the componentDidUpdate() function, you can get the data before and after the update. By comparing the data before and after, if the data changes, perform a series of operations. This indirectly implements watch event monitoring.

// 模拟vue中的watch监听
componentDidUpdate(prevProps,prevState) {
    if(prevState.a !== this.state.a) {
        console.log("a变量");
    }
}

The above are some relatively small knowledge points, which are mainly compared with vue.

Guess you like

Origin blog.csdn.net/qq_41339126/article/details/109500815