React hooks
react 无状态组件(Function)
- 只在最顶层使用 Hook:不要在循环,条件或嵌套函数中调用 Hook, 确保总是在你的 React 函数的最顶层调用他们。
- 不要在普通的 JavaScript 函数中调用 Hook。你可以
在 React 的函数组件中调用 Hook
在自定义 Hook 中调用其他 Hook
1、componentDidMount
useEffect(() => {
setState();
}, []);
2、componentDidUpdate
useEffect(() => {
setState();
}, [count]); // 只有当count发生变化时才会触发此useEffect
3、setState
const [state, setState] = useState(props.state);
4、模块调用
import { Payment } from './Payment';
<Payment state={10} /> //state=>props.state;
demo
Payment.jsx
import React, { useState,useEffect } from 'react';
export function Payment(props) {
const [count, setCount] = useState(props.state);
useEffect(() => {
setCount(12);
}, []); // componentDidMount();
useEffect(() => {
if (count < 20) {
setCount(count + 10);
}
}, [count]); // componentDidUpdate(); 当count发生变化时
const handleFunc = () => { setCount(count + 1);
// console.log(count);
return (<div>
<span>{count}</span>
<button onClick={ handleFunc }}>hahahhahahaha</button>
</div>);
}
App.jsx
import { Component } from 'react';
import { Payment } from './Payment';
class App extends Component {
render() {
return (
<Payment state={10} />
);
}
}