without with react props javascript reactjs scope react-native jsx

javascript - with - Undefined no es un objeto que evalúa this.state/this.props



setstate react (4)

Estás yendo en la dirección correcta, pero todavía hay un problema menor. Está pasando una function a su devolución de llamada de map que tiene un alcance diferente ( this ) que su componente (porque no es una función de flecha), por lo que cuando se bind(this) , se vuelve a bind(this) la devolución de llamada para usar el alcance del map . Creo que esto debería funcionar, básicamente convierte la devolución de llamada que pasas para map en una función de flecha. Además, como bind su función en el constructor, no necesita hacerlo de nuevo:

// The constructor logic remains the same // .... renderLoadingView() { return ( <View style={[styles.cardContainer, styles.loading]}> <Text style={styles.restData}> Loading ... </Text> </View> ) } _buttonPress = () => { this.props.navigator.push({ id: ''Main'' }) } renderGPSDataFromServer =() => { const {loaded} = this.state; const {state} = this.state; return this.state.dataArr.map((data, i) => { return( <View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}> <View style={styles.cardContentLeft}> <TouchableHighlight style={styles.button} onPress={this._buttonPress}> <Text style={styles.restData}>View Video</Text> </TouchableHighlight> </View> <View style={styles.cardContentRight}> <Text style={styles.restData}>{i}</Text> <View style={styles.gpsDataContainer}> <Text style={styles.gpsData}> {Number(data.lat).toFixed(2)}</Text> <Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text> </View> <Text style={styles.gpsData}> {this.calcRow(55,55).bind(this)} </Text> </View> </View> ); }); } render = ()=> { if (!this.state.loaded) { return this.renderLoadingView(); } return( <View> {this.renderGPSDataFromServer()} </View> ) }};

¿Cómo puedo vincular una función fuera del alcance en React Native? Estoy recibiendo los errores:

undefined is not an object evaluating this.state

&

undefined is not an object evaluating this.props

Estoy usando el método de renderizado para evocar renderGPSDataFromServer() cuando los datos se han cargado. El problema es que estoy tratando de usar _buttonPress() y calcRow() dentro de renderGPSDataFromServer() , pero renderGPSDataFromServer() esos errores.

he añadido

constructor(props) { super(props); this._buttonPress = this._buttonPress.bind(this); this.calcRow = this.calcRow.bind(this);

a mi constructor y he cambiado _buttonPress() { a _buttonPress = () => { y todavía nada.

Creo que entiendo el problema, pero no sé cómo solucionarlo:

renderLoadingView() { return ( <View style={[styles.cardContainer, styles.loading]}> <Text style={styles.restData}> Loading ... </Text> </View> ) } _buttonPress = () => { this.props.navigator.push({ id: ''Main'' }) } renderGPSDataFromServer =() => { const {loaded} = this.state; const {state} = this.state; return this.state.dataArr.map(function(data, i){ return( <View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}> <View style={styles.cardContentLeft}> <TouchableHighlight style={styles.button} onPress={this._buttonPress().bind(this)}> <Text style={styles.restData}>View Video</Text> </TouchableHighlight> </View> <View style={styles.cardContentRight}> <Text style={styles.restData}>{i}</Text> <View style={styles.gpsDataContainer}> <Text style={styles.gpsData}> {Number(data.lat).toFixed(2)}</Text> <Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text> </View> <Text style={styles.gpsData}> {this.calcRow(55,55).bind(this)} </Text> </View> </View> ); }); } render = ()=> { if (!this.state.loaded) { return this.renderLoadingView(); } return( <View> {this.renderGPSDataFromServer()} </View> ) }};

¿Cómo voy a arreglar esto y en este caso cuál es el problema?


Esto está sucediendo porque, la función dentro del método del map crea un contexto diferente. Puede utilizar funciones de flecha como devolución de llamada en el método de map para enlace léxico. Eso debería resolver el problema que estás teniendo.

renderGPSDataFromServer =() => { const {loaded} = this.state; const {state} = this.state; return this.state.dataArr.map((data, i) => { return( <View style={[styles.cardContainer, styles.modularBorder, styles.basePadding]} key={i}> <View style={styles.cardContentLeft}> <TouchableHighlight style={styles.button} onPress={this._buttonPress().bind(this)}> <Text style={styles.restData}>View Video</Text> </TouchableHighlight> </View> <View style={styles.cardContentRight}> <Text style={styles.restData}>{i}</Text> <View style={styles.gpsDataContainer}> <Text style={styles.gpsData}> {Number(data.lat).toFixed(2)}</Text> <Text style={styles.gpsData}>{Number(data.long).toFixed(2)}</Text> </View> <Text style={styles.gpsData}> {this.calcRow(55,55).bind(this)} </Text> </View> </View> ); }); }

Además, una vez que haya utilizado las funciones de flecha en la definición de la función de clase, no necesita vincularlas en un constructor como:

constructor(props) { super(props); this._customMethodDefinedUsingFatArrow = this._customMethodDefinedUsingFatArrow.bind(this) }

Además, una vez que haya definido las funciones de clase como funciones de flecha, no necesita usar las funciones de flecha mientras las llama:

class Example extends React.Component { myfunc = () => { this.nextFunc() } nextFunc = () => { console.log(''hello hello'') } render() { // this will give you the desired result return ( <TouchableOpacity onPress={this.myFunc} /> ) // you don''t need to do this return ( <TouchableOpacity onPress={() => this.myFunc()} /> ) } }


this.props son de solo lectura

Reaccionar documentos - componente y accesorios

Y, por lo tanto, un componente no debería tratar de modificarlos, mucho menos mutarlos como lo está haciendo aquí:

_buttonPress = () => { this.props.navigator.push({ id: ''Main'' }) }

Sugeriría usar el estado en su lugar:

_buttonPress = () => { this.setState = { ...this.state, navigator: { ...this.state.navigator, id: ''Main'' } } }

En cuanto a su problema vinculante:

el método .map toma un segundo argumento que se utiliza para establecer el valor de this cuando se invoca la devolución de llamada.

En el contexto de su pregunta, solo necesita pasar this como el segundo argumento para su método .map para vincularlo con el alcance de los componentes.


no estoy seguro de si este es el problema, pero creo que el código es incorrecto y puede estar causando el problema.

<View style={styles.cardContentLeft}> <TouchableHighlight style={styles.button} onPress={this._buttonPress().bind(this)}> <Text style={styles.restData}>View Video</Text> </TouchableHighlight> </View>

específicamente esta línea onPress={this._buttonPress().bind(this)}> está invocando la función y vinculándola al mismo tiempo.

La forma correcta de hacerlo sería tan

onPress={this._buttonPress.bind(this)}>

de esta forma, la función solo se llamará en Presionar.