亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 Gatsby 箭頭函數看不到 props 中傳遞的值,其中值是從 Promise 派生的?

為什么 Gatsby 箭頭函數看不到 props 中傳遞的值,其中值是從 Promise 派生的?

蝴蝶不菲 2022-11-03 15:04:53
有人可以解釋為什么key箭頭函數內的值未定義:// in parent componentconst 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 componentinterface 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?
查看完整描述

3 回答

?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

在 React 中,key是一個保留的 prop 名稱。

[...] 未定義試圖從組件(即渲染函數或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)


查看完整回答
反對 回復 2022-11-03
?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

你的不工作的原因:道具是綁定的,this但是你定義的回調有它自己的范圍,因此有它自己的this. 因此,您需要為該范圍提供值。您可以通過使用組件的本地狀態來做到這一點。由于 React 中有一些很好的鉤子可以讓你輕松完成,你應該使用它們來記住回調:

React.useCallback(() =>{console.log(key);}, [key]);

請注意在key更改時更新回調的依賴數組。這里的范圍很好。


查看完整回答
反對 回復 2022-11-03
?
嚕嚕噠

TA貢獻1784條經驗 獲得超7個贊

import React, { useCallback } from 'react';


const callback = useCallback(() => {

    // this isn't working, key is undefined

    console.log("value within callback: " + key);

}, [key]);


查看完整回答
反對 回復 2022-11-03
  • 3 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號