我有一个名为 First 的子组件,其实现如下:
function First(props) {
const handleButtonClick = () => {
props.positiveCallback({key: 'positive', value: 'pos'})
props.negativeCallback({key: 'negative', value: '-100'})
}
return (
<div><button onClick={() => handleButtonClick()}>FIRST</button></div>
)
}
我有 App.js 组件。
function App() {
const [counter, setCounter] = useState({positive: '+', negative: '-'})
const handleCounterCallback = (obj) => {
console.log(obj)
let newCounter = {...counter}
newCounter[obj.key] = obj.value
setCounter(newCounter)
}
const handleDisplayClick = () => {
console.log(counter)
}
return (
<div className="App">
<First positiveCallback = {handleCounterCallback} negativeCallback = {handleCounterCallback} />
<Second negativeCallback = {handleCounterCallback} />
<button onClick={() => handleDisplayClick()}>Display</button>
</div>
);
}
当在 First 组件中单击 handleButtonClick 时,它会触发多个回调,但只有最后一个回调会更新状态。
在例子中:
props.positiveCallback({key: 'positive', value: 'pos'}) // not updated
props.negativeCallback({key: 'negative', value: '-100'}) // updated
有什么想法吗?
最佳答案
两者都在更新 state
,你的问题是当你 spread
之前的状态(当你访问时它没有更新)时,最后一个正在覆盖第一个它,所以你正在传播初始状态)。一个简单的解决方法是将 counter
分成更小的部分并单独更新它们
const [positive, setPositive] = useState('+')
const [negative, setNegative] = useState('-')
//This prevents your current code of breaking when accessing counter[key]
const counter = { positive, negative }
const handleCounterCallback = ({ key, value }) => {
key === 'positive' ? setPositive(value) : setNegative(value)
}
关于javascript - react 多个回调不更新本地状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58205629/