gpt4 book ai didi

reactjs - 为什么我看不到子组件事件处理程序的父状态?

转载 作者:行者123 更新时间:2023-12-04 03:53:24 25 4
gpt4 key购买 nike

我有两个组成部分:膳食成分Ingredient 始终是 Meal 的子元素。我将下面的函数作为 Prop 传递给每个成分,例如<Ingredient deleteIngFunc={handleDeleteIng} /> .

点击 Ingredient 中的按钮,Ingredient 触发 prop.deleteIngFunc但是当我 console.debug ingsArrayCopy从功能来看,它是空的!它不应该为空,因为页面呈现时状态显然存在(即成分显示在页面上,因此状态显然不为空)

膳食.js

import React, {useState, useEffect} from 'react';
import Ingredient from './Ingredient';

function Meal(props){
const [ingArray, setIngArray] = useState([]);

function handleDeleteIng(e){
let ingsArrayCopy = [...ingArray];
console.debug(ingsArrayCopy); // empty array??
}

async function initIngs(){
let ings = props.ings.map(
ing => (
<Ingredient title={ing.title} id={ing.id} deleteIngFunc={handleDeleteIng} />
)
)

return await setIngArray(prev => ings)
}

function updateIngs(newIngObject){
let oldIngState = [...ingArray];

let newIng = <Ingredient key={newIngObject.id} id={newIngObject.id} title={newIngObject.title} />

let newIngState = oldIngState.concat([newIng]);

setIngArray(prev => newIngState);
}


useEffect(
() => {
initIngs();
},
[]
);

return (
<ul>
{ingArray}
</ul>
);
}

export default Meal;

成分.js

import React, {useState, useEffect} from 'react';
import CancelIcon from '@material-ui/icons/Cancel';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';

function Ingredient(props){

function handleDeletion(e){
e.preventDefault()
props.deleteIngFunc(e)
}

return (
<li
key={props.id}
className="ingredient-listitem"
>
<Typography className="ingredient-text">{props.title}</Typography>

<IconButton onClick={handleDeletion}>
<CancelIcon></CancelIcon>
</IconButton>
</li>
)
}

export default Ingredient;

最佳答案

不,状态的值不能在常规函数内部访问。它只能通过以下 react Hook 访问 useEffect() useCallback() useMemo()return 功能组件的声明。

例如:

function App() {
const [state, setState] = useState('initial Value')

function someFunction(){
// It's not recommended to access the state inside of this function
// cause the value of the state will always be ('initial Value')
// even if the state were updated
console.log(state)
// Why ?
// Because regular function like this cannot have dependency array
// And thus without dependency array function will not know that state has changed
}

useEffect(()=>{
// It's good if you access the value of the state here
// It will be assured it will always have the updated value
console.log(state)
},[state])


return (
// You can also access the value of the state inside return statement
<>
{console.log(state)}
<SomeComponent props={state}/>
</>
)
}

另外:您可以在常规函数上设置状态,但不能访问或读取常规函数上的状态

我包含了一个针对您的问题的演示的 codesandbox 链接

https://codesandbox.io/s/accessingstate-03hud?file=/src/App.js

关于reactjs - 为什么我看不到子组件事件处理程序的父状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64112072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com