Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am having a problem with react native and am kinda stuck on to why this isn't working. I am trying to update my state a friends page using the onChangeText property of the input component from react-native-elements.

export default class FriendsPage extends Component {
    
    constructor(props) {
        super(props);
        this.state = {
            search:'',
            loading:false
        };
    }
    findFriend(){
        //Does stuff
    }
  
    renderButtonOrLoading() {
        if(this.state.loading){
            return <Text>Loading</Text>
        }
        return(
            <View style={styles.container}>
                <Button title = "Search" onPress={()=>this.findFriend()} styles={styles.button}/>
            </View>
        );
    }
    render(){
      console.log(this.search)
        return(
            <View style={styles.container}>
              <TextInput style={styles.input}
                  placeholder='username'
                  onChangeText={search =>this.setState({ search})}/>
                     
              {this.renderButtonOrLoading()}
            </View>

        
        );
    }
}

const styles = StyleSheet.create({
    container:{
        marginTop: 100,
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',

    }
});

My problem is that every time that I call the function findFriends(), I get an error that sais that this.search is undefined. I tried to console log this.search during render and it just seems to stay at undefined each render cycle. I have a feeling I should be using props somehow but am not sure as I am relatively new to react.

Edit: Thanks for all the answers, I was trying to call this.search although it is supposed to be this.state.search and this is what broke my code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
485 views
Welcome To Ask or Share your Answers For Others

1 Answer

It is unclear if the variable search is the same as the one in the state. If it is, this code will not work.

onChangeText={search =>this.setState({ search})} // setting a state to itself won't work

If it is a separate variable, you have called setState incorrectly. I recommend changing the name of the variable. The setState call should look more like this:

onChangeText={ s => this.setState( { search: s } );

search is undefined (falsey) because you set it to ' ' in your state. For a class-based React apporach, you can use the getDerivedStateFromProps() method (if you are passing a search term in from the props).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...