Reputation: 800
Is it possible for say two states that update a single view/component? How do we do this in react?
this.state({
dog: 'Canny'
person: 'Brian'
})
<Text>{blank} likes beans.<Text>
For example, when this.state.dog updates, the field will read 'Canny likes beans', when this.state.person updates, the field will read 'Brian likes beans'. Is there a way to do this?
Edit: This is useful for the case where the view only has one window to display updates of two states, and I understand you can use a render function to achieve this, but is there a simple 'first principles' way in react to do this?
Upvotes: 1
Views: 1652
Reputation: 222840
This should be done by introducing another state property, personOrDog
:
<Text>{this.state.personOrDog} likes beans.<Text>
There's no straightforward way to check previous and current person
and dog
state to calculate personOrDog
. Previous and current states are available in shouldComponentUpdate
but the use of setState
to set personOrDog
there is discouraged because it abuses this lifecycle hook.
This means that this issue should preferably be addressed in a place where a state is updated:
this.setState({
dog: 'Canny',
personOrDog: 'Canny'
});
To make code DRYer, a helper can be used to set these properties, e.g.:
const personOrDog = (key, value) => ({
[key]: value,
personOrDog: value
});
...
this.setState(personOrDog('dog', 'Canny'));
Upvotes: 3
Reputation: 478
As for me, it is usual situation for React js. Whenever you change state, innerHTML of your Text component re-renders.
this.state({
name:
table:
})
<Text>
Now current state.name is: {this.state.name}, current state.table: {this.state.name}
</Text>
PS: and don't forget to close tags: < / Text>
Upvotes: 0