-
Notifications
You must be signed in to change notification settings - Fork 39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
React避坑指南 #53
Comments
useRef为什么可以保证事件处理器中的对象不为null?通常来说,useRef用于引用组件的Dom节点。Vue中的ref则是引用一个vue组件。与Vue不同,react中的ref不仅仅是引用Dom节点,还可以生成一个内存不变的对象引用。 使用useState导致的空指针示例const [foo, setFoo] = useState(null);
const handler = () => {
setFoo("hello")
}
useEffect(() => {
return () => {
// 无论怎样foo都是null,给useEffect的deps加入foo也不行
if (foo === "hello") {
// do something...
}
}
}, []) 使用useRef的正确示例const foo = useRef(null)
const handler = () => {
foo.current = "hello"
}
useEffect(() => {
return () => {
// foo.current为hello
if (foo.current === "hello") {
// do something...
}
}
}, []) useRef解决空指针问题的原因是什么?
总结起来就是:useRef生成的对象,在组件生命周期期间内存地址都是不变的。 const refContainer = useRef(initialValue); useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component. This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render. |
React中的事件绑定
|
React除了可以通过props传递数据以外,如何通过context方式传递数据?假设组件层级较深,props需要一级一级往下传,可以说是props hell问题。 组件定义context部分import * as React from 'react'
// myContext.ts
interface IContext {
foo: string,
bar?: number,
baz: string
}
const myContext = React.createContext<IContext>({
foo: "a",
baz: "b"
})
interface IProps {
data: IContext ,
}
const myProvider: React.FC<IProps> = (props) => {
const {data, children} = props
return <myContext.Provider value={data}>{children}</myContext.Provider>
}
export default myProvider;
export function useMyContext() {
return useContext(myContext)
} 使用组件和context部分<!-- 组件包裹 -->
import myProvider from './myContext.ts'
<myProvider data={{foo: "foo", baz: "baz"}}>
<div className="root">
<div className="parent">
<Component1 />
<Component2 />
</div>
</div>
</myProvider> // Component1
import {useMyContext} from './myContext.ts'
const {foo, baz} = useMyContext()
const Compoonent1 = () => {
return (<div>{foo}{baz}</div>)
}
export Component1 |
onClick={handleClick}
与onClick={handleClick('pop')}
区别是什么?The text was updated successfully, but these errors were encountered: