React development tips

1, short circuit write instead of if

// Control whether the element is displayed by judging whether the value exists or not
/ / General trinocular operation can achieve this effect, some can be replaced by short circuit
// Use !! to turn it into a boolean to avoid pits
Const flag = 0;
!!flag && <div></div>

2, use es6 new feature delivery component props

const {data, type} = this.state;
// General method
<Demo data={data} type={type}/>
// es6 method
<Demo {...{data, type}}/>

3, use the es6 rest parameter (in the form of... variable name) to pass a variable number of props

// to define subcomponents
Const Demo = ({ prop1, prop2, ...restProps }) => (
    <div>{ restProps.text}</div>
)
// Parent component uses Demo
<Demo prop1={xxx} prop2={xxx} text={xxx}/>

4, other usages of setState

// A general way to change the state value
Const { data } = this.state;
this.setState({ data: {...data, key: 1 } });
// Another way to change the value of state by callback
this.setState(({ data }) => ({ data: {...data, key: 1 } }));
// still alright
this.setState((state, props) => {
    Return { counter: state.counter + props.step };
});

5, React Performance Optimization

// There are many ways to optimize React performance.
// The common one is to judge in the lifecycle function shouldComponentUpdate
// Some values ​​or properties to control whether the component is rendered again.
/ / Judging the general string, number or basic objects, arrays are still better
// That nested object or array is more troublesome, for this
// Recommend using edash (or other similar library) isEqual to judge nested arrays or objects
shouldComponentUpdate(nextProps, nextState) {
    If (_.isEqual(nextState.columns, this.state.columns)) return false;
    Return true;
}

6, subcomponent changes the parent component's state

// The subcomponent changes the state of the parent component. There are many ways to set a generic function in the parent component.
/ / Similar: setParentState, through the sub-component callback processing, you can more convenient unified processing
// parent component
State = {data: {}};
setParentState = obj => {
    this.setState(obj);
}
// Subassembly
onClick = () => {
    this.props.setParentState({ data: xxx });
}