我正在尝试从子元素中更新父元素的状态。
我希望更新在每个子元素安装后立即发生,因此我使用useEffect钩子并从那里调用更新函数setData(从父级传递下来)。
然而,似乎每个随后被安装的子元素都没有注意到先前安装的子元素对数据所做的更改。也就是说,它对一个空data数组进行操作,而对于第二个、第三个和第四个元素,该数组不应再为空。
我相信这是因为setData仅在所有元素安装后才计划执行。这个对吗?如果是这样,我该如何解决这个问题?
function Parent() {
const [data, setData] = React.useState([])
function changeData(index, value) {
logData()
let new_data = Array.from(data)
new_data[index] = value
setData(new_data)
}
function logData() {
console.log(data)
}
let children = Array(4).fill(null).map((item, index) => {
return <Child id={index} changeData={changeData} />
})
return (
<div>
{children}
<button onClick={logData}>Log data</button>
</div>
)
}
function Child(props) {
const ref = React.useRef(null)
React.useEffect(() => {
props.changeData(ref.current.id, ref.current.id)
}, [])
function onClickHandler(e) {
let element_id = e.target.id
props.changeData(element_id, element_id)
}
return (
<button ref={ref} id={props.id} onClick={onClickHandler}>Child</button>
)
}
ReactDOM.render(<Parent />, document.getElementById('root'))
<!DOCTYPE html>
<html>
<body>
<head>
<script src="https://unpkg.com/react@^16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.13.0/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
</head>
<div id="root"></div>
</body>
</html>
MM们
相关分类