RiseAgainst RiseAgainst - 2 years ago 110
Javascript Question

Set dynamic state name based on the delivered parameter in react-native

I'm new to developing in react-native. Right now I'm trying to code a simple Scoreboard for the Dart game "Cricket" to get my feet wet.

It is basically a game where you need to hit the 15-20 and bullseye fields 3 times to close them. If you hit them more than 3 times you can collect points.

My first version of the app is working but its ugly and uses lots lines of code. I made a function for every point field (15-20 + bullseye) to add the points. Like:


this.state.indicator = "x";

if(this.state.tapped_20 > 1){
this.state.indicator = "xx";
if(this.state.tapped_20 > 2){
this.state.indicator = "xxx";
if(this.state.tapped_20 > 3){
this.state.points = 20 + this.state.points



points: this.state.points,
tapped_20: this.state.tapped_20+1,


this.state.indicator_19 = "x";

if(this.state.tapped_19 > 1){
this.state.indicator_19 = "xx";
if(this.state.tapped_19 > 2){
this.state.indicator_19 = "xxx";
if(this.state.tapped_19 > 3){
console.log("Ab hier Punkte..")
this.state.points = 19 + this.state.points



points: this.state.points,
tapped_19: this.state.tapped_19+1,

Etc.. My approach was now to overgive an parameter with the function. So i just have one function which adds the points based on the given parameter. Like so:

<TouchableHighlight style={styles.button}
onPress={this.testfunc.bind(this, 20)}
<Text style={styles.buttonText}> 20 Test</Text>

Which calls the the function:

testfunc(i) {

window['this.state.indicator_' + i ] = 'test'


When i debug it in the Browser it states that the console.log(this.state.indicator_20) is undefined.

It seems it does not work with this.state... Does anyone know how to solve such a problem?

Answer Source

First, you should never have to refer to window in React Native. Consider that a red flag.

Second, you cannot evaluate the properties on objects in this fashion: window['this.state.indicator_' + i ]. You refer to a property called "foo" on an object called "bar" thusly: bar['foo'] and you cannot reference any deeper (that is, no bar['foo.baz']).

Anyway, react provides setState for this:

testfunc(i) {
  const update = {};

  update['indicator_' + i] = 'test';


Then refer to this.state.indicator_X in your render, and it'll update as expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download