Welcome to this week's TWIL journey, where continuous growth is part of our DNA! Emily provides two insightful snippets to enhance your tech toolkit. First up, learn the quirks of Truthy Dictionary Keys and how Python determines the unique keys in a dictionary - a crucial piece of information for any Pythonista. Then, advance your understanding of React's setState
method with SetState Argument for Previous State, grasping the use of prevState
for more predictable state transitions. Whether it's a pythonic puzzle or a React revelation, these micro-learnings pave the way for smarter coding.
Truthy Dictionary Keys
Overriding:
>>> d = {'a': 0, 1: 'one', True: "true"}
>>> d
{'a': 0, 1: 'true'}
Accessing:
>>> d = {'a': 0, 1: 'one'}
>>> d
{'a': 0, 1: 'one'}
>>> d[True]
'one'
- Python
SetState Argument for Previous State
Previously, we would do something like:
const { num } = this.state
this.setState({
num: num + 1,
})
setState
can also take a function instead of an object, which provides us with the previous state as an argument:
this.setState(prevState => ({
num: prevState.num + 1,
}))
// With parameter destruction
this.setState(({ num: prevNum }) => ({
num: prevNum + 1,
}))
- React