有人可以解释为什么箭头函数中key
的值未定义:
// in parent component
const Parent = () => {
const [key, setKey] = useState<string>();
// this contains an expensive function we only wish to execute once on first load
useEffect(() => {
// has some promise that will call within a `then()`
setKey(someVal);
}, []};
// within render
< MyComponent key={key}/>
}
// within child component
interface Props {
key: string;
}
const MyComponent = ({key}: Props) => {
// this works, I can see the correct value `someVal`
console.log("value when rendered: " + key);
const callback = () => {
// this isn't working, key is undefined
console.log("value within callback: " + key);
}
// within render, when something calls callback(), key is undefined, why?
}
我可以看到key
在调用渲染时有一个值,但key
是未定义的。我试过用let callback =
代替const
,但没有运气。请问我如何访问key
?
在 React 中,key
是一个保留的道具名称。
[...]尝试从组件(即渲染函数或
propTypes
(访问this.props.key未定义
https://reactjs.org/warnings/special-props.html
这可能就是它在后续渲染中不起作用的原因——我很惊讶它在第一次渲染中根本不起作用!
这工作正常:
// https://codepen.io/d4rek/pen/PoZRWQw
import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'
const Child = ({ id }) => {
console.log(`within component: ${id}`)
const cb = () => console.log(`in callback: ${id}`)
return <button onClick={cb}>Click me</button>
}
const Parent = () => {
const [id, setId] = React.useState(null)
React.useEffect(() => {
setId(nanoid(6))
}, [])
return (<Child id={id} />)
}
ReactDOM.render(<Parent />, document.body)
import React, { useCallback } from 'react';
const callback = useCallback(() => {
// this isn't working, key is undefined
console.log("value within callback: " + key);
}, [key]);
你的不工作的原因:道具绑定到this
但你定义的回调有自己的范围,因此有自己的this
。因此,您需要为该范围提供值。可以使用组件的本地状态来执行此操作。由于 React 中有一些不错的钩子来简化,您应该使用它们来记住回调:
React.useCallback(() =>{console.log(key);}, [key]);
请注意在key
更改时更新回调的依赖项数组。这里的范围很好。