background

Recently, due to the schedule of the project and personnel problems, I was temporarily engaged in the front-end development of React. I haven’t developed React for a long time, so IT was strange to handle React. In addition, ReactHook, who was new to React, encountered a lot of problems.

Basic front-end problems

“And “” and “”

In our project, “” is generally used uniformly, and” “is prohibited. React may be used when writing long characters. React is not used as much as JQuery.

Array operations

With ES6, the ease of manipulating arrays has been greatly improved

  • Map, as it is almost universally known, is primarily used to traverse an array and has only one input parameter
  • Foreach: unlike Java foreach, foreach has index as its second parameter in addition to value
  • Filter: indicates that data is filtered. Return 0 indicates that data is removed and 1 indicates that data is reserved
  • Find, an API for finding values in arrays

Expansion operator

Object expansion a={a:123}; B = {… A,b:456}//{a:123,b:456} array a =[1,2,3,4]; B =[… A,5,6,7]//1,2,3,4,5,6,7 string expansion A= “ABC”; B = [… a, ‘d’]. //a,b,c,d

React common call problems

How do I call the parent component method or property props

To use:

  <CustomPlotWidget
                    onClear={() = > {
                        form.resetFields()
                    }}
                    cpId={cpId}
                />
Copy the code

In the component

const {plotting, viewer, onChange, initialValue, cpId, plotFileName, onClear} = props;
Copy the code

How do I invoke child component methods

The parent component

const disasterListComponent = useRef();
 	disasterListComponent.current.hideUpdate()
<DisasterList ref={disasterListComponent} />;
Copy the code

Child components


const DisasterList =(props,ref) = >{
    useImperativeHandle(ref, () = > ({
        method: xxx,
    }));
}
export default forwardRef(DisasterList);
Copy the code

How to extensively call a component’s methods

Redux

Overall incident management

const index = (state = indexInitialState, action) = > {
    switch (action.type) {
case ActionTypes.DEFINE_SUPER_MAP:
            return {
                ...state,
                superMap: action.value
            };
        default:
            return state
    }
}
Copy the code

Within the invoked component, call Dispatch

const onMapIniComplete = (superMap) = > {
        dispatch(Actions.defineSuperMap(superMap));
    };
Copy the code

The caller

const superMap = useSelector(state= > state.index.superMap);
sueprMap.XXX();
Copy the code

ReactHook FAQs

Array modification problem

This is probably one of the most problematic areas for unfamiliar people to write

[array,setArray]=useState([]);
 useEffect(() = > {
       console.log(array)
    }, [array])
array.push("hello");
setArray(array)// Console printing in useEffect is not triggered here
Copy the code

Correct term

[array,setArray]=useState([]);
 useEffect(() = > {
       console.log(array)
    }, [array])
array.push("hello");
setArray([...array])// This triggers the console print inside useEffect
Copy the code

You’re essentially creating a new array, making Pointers change, forcing a state change.

The updated value of state could not be obtained in the callback

Error writing

[cpTopic,setCpTopic]=useState("");
 useEffect(() = > {
        if(! cpTopic) {return;
        }
        let apiUtil = new ApiUtil();
        let client = apiUtil.mqttInit();
        client.on('connect'.function () {
            client.subscribe(cpTopic);
        });
        // let mqttCount = 0;
        client.on('message'.(topic, message) = > {
          console.log(cpTopic);
      });
        setMqttClient(client);
        return () = > {
            client.unsubscribe(cpTopic);
        };
    }, [cpTopic])

setCpTopic("hello")
Copy the code

Most people would think it would print hello, but it would print “”, because cpTopic can’t get updates to cpTopic.

Correct term

[cpTopic,setCpTopic]=useState("");
[messageEvent,setMessageEvent]=useState({});
 useEffect(() = > {
        if(! cpTopic) {return;
        }
        let apiUtil = new ApiUtil();
        let client = apiUtil.mqttInit();
        client.on('connect'.function () {
            client.subscribe(cpTopic);
        });
        // let mqttCount = 0;
        client.on('message'.(topic, message) = > {
        setMessageEvent({content:message});
      });
        setMqttClient(client);
        return () = > {
            client.unsubscribe(cpTopic);
        };
    }, [cpTopic])
    useEffect(() = > {
            log.console(messageEvent.content);
    }, [messageEvent])
Copy the code