> 沒有this,不能使用生命周期方法
>
**例子**
~~~
import React,{
memo,
createContext,
forwardRef,
useState,
useEffect,
useCallback,
useContext,
useRef,
useImperativeHandle
} from 'react';
const TestContext = createContext('default');
const Comp = memo((props)=>{
useEffect(()=>{
console.log('comp updated');
});
const updateValue = ()=>{
props.onClick(props.value + '1')
};
return<button
style={{width:'200px',height:"40px",background:'red',margin:'20px'}}
onClick={updateValue}>
comp button{props.name}
</button>
});
const ContextComp = forwardRef((props,ref)=>{
const context = useContext(TestContext);
useEffect(()=>{
console.log('context comp updated')
});
useImperativeHandle(ref,()=>({
method(){
console.log('method invoked')
}
}));
return <p>{context}</p>
});
export default function App() {
const [ name,setName ] = useState('freya');
const [ compName,setCompName ] = useState('compName');
const ref = useRef();
useEffect(()=>{
console.log('component update');
ref.current.method();
return ()=>{ //解除綁定
console.log('unbind');
}
},[]); // 去掉這數組就會每次都調用。
const compCallback = useCallback((value)=>{
setCompName(value);
},[compName]); //演示沒有[compName] 每次Comp都會調用effect
return (
<div className="App">
<input style={{width:'200px',height:"40px",border:'1px solid red',margin:'20px'}}
type="text" value={name} onChange={e => setName(e.target.value)}/>
<Comp name={compName} onClick = {compCallback}/>
<TestContext.Provider value ={name} >
<ContextComp ref = {ref}/>
</TestContext.Provider>
</div>
);
}
~~~
源碼 路徑
```
packages/react/src/ReactHooks.js
```
- 說明
- react源碼
- 問答
- 慕課網視頻
- 第二章:基礎知識
- 001.ReactElement
- 002.react-component
- 003.ref
- 004.forwardRef
- 005.context
- 006.concurrentMode
- 007.supense和lazy
- 008.hooks
- 009.children
- 010.memo
- 011.others
- 第三章:react的更新
- 001.react-dom-render
- 第四章:Fiber Scheduler
- 第五章:各類組件的Update
- 第六章:完成節點任務
- 第七章:commitRoot
- 第八章:功能詳解:基礎
- 第九章:suspense and priority
- 第十章:功能詳解:Hooks
- 001.基礎知識
- 002.hook
- 003.RootFiber
- 004. hydrate
- react
- 高階組件
- react基礎
- Github面試題目