I am having trouble getting my head around state management in React.
I'm tempted to say its rubbish but I know in truth I'm just not understanding some fundamental thing. I've set up a simple example on Plunker that basically illustrates what I'm trying to do
const Hello = ()=>{
const [myArr, setMyArr] = useState([]);
const addToArr = ()=>{
setMyArr(arr => arr.concat(arr.length+1));
}
const clearArr = ()=>{
setMyArr(arr => [])
}
useEffect(()=>{
console.log(myArr);
}, [myArr]);
return <div>
<button onClick={addToArr}>Add</button>
<button onClick={clearArr}>Clear</button>
<button onClick={()=>{
clearArr();
addToArr();
}}>Clear Then Add</button>
</div>
}
export default Hello;
Run the preview and you'll see three buttons. With the dev tools console open click the buttons.
Add and Clear work as expected and result in an array with 1 additional item or an empty array.
Clear Then Add is where I am confused. The final outcome is correct, an array with 1 item, but I would expect to see an empty array logged first.
I've read a bunch of stuff about how state updates are async and React is trying to minimise rerenders and what-have-you but in my instance I need to respond to that empty array.
I have a few components that watch the list and some of then need to know if updates are taking the form of items being added to an existing list or items being added after the list was cleared.
I've also read that you should not call methods of child components in React.
那么,有没有办法对第一次清理名单做出回应?
另外,我不明白的基本概念可能是什么,因为在我看来,如果你无法知道它们何时完成或无法倾听它们何时发生,拥有异步状态更新似乎是一件非常令人头疼的事情. 再说一次,我确信我的 struct 才是问题所在,但这真的让我很恼火,我需要咆哮.