1 回答

TA貢獻1886條經驗 獲得超2個贊
根據當前狀態更新狀態時,您應該始終使用setState
. 有關詳細信息,請參閱為什么 setState 給了我錯誤的值。
如果您不使用回調版本,setState
對依賴于當前狀態的連續調用將相互覆蓋,如果它們被 react 批處理,可能會導致不正確的狀態。
function changeData(index, value) {
logData()
setData(current => {
// current is the current state including all previous calls to setState in this batch
const new_data = Array.from(current);
new_data[index] = value;
return new_data;
});
}
更新示例:
function Parent() {
const [data, setData] = React.useState([])
function changeData(index, value) {
logData()
setData(current => {
const new_data = Array.from(current);
new_data[index] = value;
return 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/[email protected]/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/babel.js"></script>
</head>
<div id="root"></div>
</body>
</html>
編輯useEffect
:我創建了一個帶有可能解決方案的沙箱,您的孩子不需要:
添加回答
舉報