create-react-app myapp
cd myapp
npm syart
import { useState } from 'react';
function App() {
// 返回一个数组,第一个值是state, 第二个值修改 state 的方法
const [ classComName, setClassComName ] = useState(() => 'cc');
const handleClick = (res) => {
setClassComName(() => res)
}
return (
<div className="App">
<ClassCom name={classComName} onClick={handleClick} />
<FuncCom />
</div>
);
}
export default App;
static getDerivedStateFromProps(props, state) {
console.log('getDerivedStateFromProps')
return {
nameList: props.name.split('')
}
}
UNSAFE_componentWillMount
shouldComponentUpdate() {
return true;
}
* 改变界面,要用 state 。调用 setState 的方法去处理。
export default class ClassCom extends Component {
constructor(props) {
super(props);
this.state = {
number: 0,
msg: 'hello aaa',
nameList: [],
}
}
// static getDerivedStateFromProps(props, state) {
// console.log('getDerivedStateFromProps')
// return {
// nameList: props.name.split('')
// }
// }
handleClickFn = function(){
//省略代码,此处只是为了区分和箭头函数的区别,作用域不同,传参的时候,需要改变this指向
}
handleClick = (type) => {
console.log('click', type)
this.setState({
number: this.state.number + ( type === 'plus' ? 1 : -1),
})
}
handleChange = (event) => {
this.setState({
msg: event.target.value
})
}
render() {
const { msg, number, nameList } = this.state;
const { name, onClick } = this.props;
return (
<div>
{this.xxx}
<div>{name}--{number}</div>
<div>
{nameList.map(item => <div key={item}>{item}</div>)}
</div>
<button onClick={() => { this.handleClick('plus') }}>+</button>
<button onClick={() => { this.handleClick('minus') }}>-</button>
<input value={msg} onChange={this.handleChange} />
{/* 子组件往父组件传值 */}
<button onClick={() => { onClick('父组件res') }} >父组件响应</button>
</div>
)
}
}
useState
[state,dispatch] = useState(initState)
- state :作为组件状态,提供ui渲染视图
- dispatch :用户修改state的方法,同时触发组件更新
- initState :初始值
const [funcName , setFuncName] = useState(()=>'initName')
const handleClick = ()=>{
//setFuncName('newName')
setFuncName(()=>'newName')
}
export default function FuncCom() {
const [ number, setNumber ] = useState(0);
const [ msg, setMsg ] = useState('hello luyi');
const [ list, setList ] = useState([]);
return (
<div>
<div>函数组件--{number}</div>
<button onClick={() => { setNumber(number + 1) }}>+</button>
<button onClick={() => { setNumber(number - 1) }}>-</button>
<input value={msg} onChange={(e) => setMsg(e.target.value)} />
</div>
)
}
//处理副作用
useEffect(()=>destory,deps)
- ()=>destory,即callback,第一个参数,是一个函数
- destory作为callback的返回值,在下一次callback执行前调用
- deps 第二个参数,是一个数组,数组的值发生改变,执行上一次的destory,并再次执行callback
useEffect(()=>{
console.log('callback')
return ()=>{
console.log('destory')
}
},[])