Search code examples
androidreact-nativecreate-react-native-app

Create react native app, development and production differences in dynamically generated components


I'm dynamically creating components in create-react-native-app. Everything is working fine using the expo app for testing in Development mode using npm start, and connecting with an android phone.

If I switch it to Production mode, or try to build the apk as a Standalone app the object is not created on the Button press.

This is my first project with React Native, and I don't know how to debug this. I've also been unable to find any information about what the differences between these two modes might be that would lead to this.

Here the relevant code:

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.updateState = this.updateState.bind(this);
    this.state = {
      knobs: [],
      key: 1
    }
  }

  add = () => {
    let key = this.state.key + 1
    let knob = (<Object key={key} updateState={this.updateState}/>);
    let knobs = this.state.knobs;
    knobs.push(knob);
    this.setState({knobs: knobs, key: key})
  }

  render = () => {
    return ([<View>
      {this.state.knobs}
      <Button onPress={() => this.add()} title='add thing'/>
    </View>
      ]);
  }
}

Solution

  • Oh, so in the end I rewrote the whole bit.

    Moving the objects to be created into the render function.

    export default class App extends React.Component {
      constructor() {
        super();
        this.state = {
          things: []
        }
        this.key = 0;
      }
    
      add = () => {
        let addThing = { key: this.key }
        this.setState({ things: [ ...this.state.things, addThing ] })
        this.key = this.key + 1;
      }
    
      render() {
        let newThings = this.state.things.map((key) => {
          return (
            <Text key={key}>New Thing.</Text>
          );
        });
        return (<View style={styles.container}>
          {newThings}
          <Button onPress={() => this.add()} title='add thing'/>
        </View>);
      }
    }
    

    This functions as expected in Production mode and as an App;)