1. read-only nature of prosp
1.1 pure functions
personal understanding: pure functions are functions that do not change the input parameters inside the function, and the same input will always get the same output, and there are no side effects during execution.
the side effect here refers to the fact that the function produces external observable changes during execution.
Common Side Effects
(1)Making HTTP Requests
(2)Manipulating the DOM
(3)Modifying External Data
(4)Console.log() Printing Data
(5) Calling Date.now() or Math.random()
Of the two functions in the following code, the sum function is a pure function because it does not attempt to change the input parameter, and the same input parameter always returns the same result after multiple calls. In contrast, withdraw is not a pure function because it changes its own entry parameters. In addition, xAdd is not a pure function, because during the execution of the program, the variable a is likely to change, then the output of the function will change.
function sum(a, b) {
return a+b;
}
function withdraw(account, amount) {
account.total -= amount;
}
let a = 1;
function xAdd(x) {
return x + a;
};
xAdd(1); //2
1.1.1 benefits of pure functions
- it is easier to test, the results only depend on the input, and the output can be ensured to be stable when testing
- it is easier to maintain and refactor, we can write higher quality code
- it is easier to call, we don’t have to worry about what side effects the function will have
- the result can be cached because the same input will always get the same output
Many of the basic methods of arrays are pure functions, such as map, forEach, and so on
In React, it also follows that “all react components must protect their props from being changed like pure functions.”
1.1.2 pure function components
// Use pure functions to create components
function Header(props) {
return <h2>{props.text}</h2>
}
// Use the Class (class) component to create components:
class Header extends React.Component {
render() {
return <h1>{this.props.text}</h1>
}
}
advantages of pure function components
- no side effects, we do not have to worry about some of the problems that are difficult to catch caused by side effects
- the syntax is more concise, the readability is good, the amount of code is relatively small, and it is easy toreuse
- the memory is small, and there is no life cycle and state management, which improves performance
pure function components also have their own disadvantages, for example: there is no life cycle. fortunately, we now have a good solution – react-hooks. with the hooks function, we can use methods such as equivalent to life cycle, state management, etc. in the function components.
2. conditional rendering
you can use variables to store elements, which can help you conditionally render part of a component that doesn’t change as a result.
const renderPartOne = useMemo(
()=>{
// code here
return something;
},[]
)
// or
const button = <LogoutButton onClick={this.handleLogoutClick} />;
3. controlled components & uncontrolled components
There are two types of components in React, namely (1) components that leave state changes handled by React and (2) components obtained by ref references. The former is a controlled component, while the latter is an uncontrolled component. The state of an uncontrolled component is stored in the component itself, and when needed, queries the DOM via ref and looks up its value.
in most cases, it is recommended to implement forms using controlled components. in a controlled component, form data is controlled by the component. in an uncontrolled component, the form component is controlled by the dom itself
in react, the so-called controlled and uncontrolled components are for forms. the concept of controlling is that for a component, its value can only be set by the user, not by code.
- form elements depend on state, form elements need default values to be mapped to state in real time, that is, the controlled component, which is similar to two-way binding.
- For controlled components, the value entered is always driven by React’s state.
3.1 controlled components
there is an input box in the code, and the interface shows the contents of the input box. as the contents of the input box change, the text above changes accordingly. the value of the form component input is processed by react via the onchange callback; react gets the value of the form (e.target.value) and saves it to the state variable name. the interface displays content by reading the component status name, so the name changes are triggered
hello {name}
re-render of .
export default function App() {
const [name, setName] = useState('');
const handleNameChange = e => {
setName(e.target.value);
}
return (
<div className="App">
<div>hello {name}</div>
name:<Input onChange={handleNameChange} />
</div>
);
}
3.2 uncontrolled components
Uncontrolled components store data in the dom rather than within the component, which is more similar to traditional HTML form elements.
- the value of an uncontrolled component is not controlled by the component’s own state and properties
- uncontrolled components use ref to get element data from the dom
The page contains an input box and a button that gets the value of the input element through ref; the input value is changed by the user, clicking the submit button, and the DOM element is obtained through ref in handSubmit, and the value of the input box is read. Changes in the input box are not controlled by the component, but are obtained via ref, i.e. read directly in the dom.
export default function App() {
const eleRef = useRef(null);
const [submitContent, setSubmitContent] = useState("");
const handleSubmit = () => {
// Get the value of the input box by ref
const content = eleRef.current?.value;
setSubmitContent(content);
};
return (
<div className="App">
<input ref={eleRef} />
<Button type="primary" onClick={handleSubmit}>
submit
</Button>
<div>{submitContent ?? ""}</div>
</div>
);
}
3.3 summary
Components in React are divided into controlled and uncontrolled.
- two main points for controlled components:
- The component’s value property is bound to the state in React
- Changes to the onChange event handling value are declared within the component
- Uncontrolled components are more like traditional HTML form elements, where data is stored in the DOM rather than inside components, and the way to get data is through ref references
- some suggestions:
- use controlled components whenever possible
- A controlled component is one that delegates state to React and can be any element, not just a form element
- for pages with a large number of form elements, using controlled components can make the program cumbersome and difficult to control, and it is wiser to use uncontrolled components
- In controlled components, the data flow is one-way (state is the source of change), so setState should be used when changing state, not force assignment
- Refs cannot be used with functional components because functional components have no instances
- Inside functional components, Refs can be used