The main issue is you are expecting setCount
to be happening immediately although it is an asynchronous action. The problem is in your <Child />
component in the below code:
const updateCount = () => {
setCount((count) => count + 1)
return props.updateCount(count)
}
Technically you are expecting count
to be updated and passed to props.updatedCount
meanwhile it's still has the previous value.
Also which is not related to the issue but you don't really need to return from the function where you update the state, so just removed return
keyword.
There are different options to solve this issue.
- Using still the separated states as in your code:
Simply calling exactly the same way the props.updateCount
as the other setState
as:
const updateCount = () => {
setCount((count) => count + 1)
props.updateCount((count) => count + 1)
}
- Keeping one state in
<Parent />
and passing down through props:
So mainly the solution would be:
export const Parent = (props) => {
const [count, setCount] = React.useState(0);
return (
<View>
<Text>Parent: {count}</Text>
{/* passed here count as well: */}
<Child updateCount={setCount} count={count} />
</View>
);
};
// destructure here updateCount and count
const Child = ({ updateCount, count }) => {
return (
<View>
{/* using here count from parent */}
<Text>Child: {count}</Text>
{/* calling here updateCount from the props as: */}
<Button title="add" onPress={() => updateCount((count) => count + 1} />
</View>
);
};
- The third option would be to use
Context
API:
By using Context
you can do the following, see from the documentation as:
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Usually I like to use Context
once we have more complex component tree than the current one. So I suggest to go with keeping one state option.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…