函数组件
const Hello = (props)=>{
return <div>{props.msg}</div>
}
const Hello = props=> <div>{props.msg}</div>
function Hello(props){
return <div>{props.msg}</div>
}
函数组件代替class组件
面临两个问题
没有state
- React v16.8.0推出了Hooks API
- 其中有一个API叫做useState可以解决这个问题
- 代码示例
const React = window.React;
const ReactDOM = window.ReactDOM;
class App extends React.Component{
constructor(props){
super(props);
this.state = {n:1};
}
onClick=()=>{
this.setState(state=>({
n:state.n+1
}))
}
render(){
return <div>
{this.state.n}
<button onClick={this.onClick}>+1</button>
</div>
}
}
const App = props =>{
const [n,setN] = React.useState(0);
const onClick = ()=>{
setN(n+1);
}
return <div>
{n}
<button onClick={onClick}>+1</button>
</div>
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App/>,rootElement);
没有生命周期
-
- React v16.8.0推出了Hooks API
-
- 其中有一个API叫做useEffect可以解决这个问题
const React = window.React;
const ReactDOM = window.ReactDOM;
const App = props =>{
const [n,setN] = React.useState(0);
const onClick = ()=>{
setN(n+1);
}
React.useEffect(()=>{
console.log("use Effect");
},[n])
return <div>
{n}
<button onClick={onClick}>+1</button>
</div>
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App/>,rootElement);
const React = window.React;
const ReactDOM = window.ReactDOM;
const Child =(props)=>{
React.useEffect(()=>{
console.log("use Effect");
return ()=>{
console.log("销毁了");
}
})
return (
<div>Child</div>
)
}
const App = props =>{
const [childVisible,setChildVisible] = React.useState(true);
const hide =()=>{
setChildVisible(false);
}
const show = ()=>{
setChildVisible(true);
}
return (<div>
{childVisible ? <button onClick={hide}>hide</button>:<button onClick={show}>show</button>}
{childVisible ? <Child />: null}
</div>)
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App/>,rootElement);
自定义 Hook 之 useUpdate
const React = window.React;
const ReactDOM = window.ReactDOM;
const useUpdate = (fn,array)=>{
const [count,setCount] = React.useState(0);
React.useEffect(()=>{
setCount(x => x+1)
},[...array])
React.useEffect(()=>{
if(count > 1){
fn()
}
},[count,fn])
}
const App = props =>{
const [n,setN] = React.useState(0);
const onClick = ()=>{
setN(n+1);
}
useUpdate(()=>{
console.log("变了")
},[n])
return <div>
{n}
<button onClick={onClick}>+1</button>
</div>
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App/>,rootElement);