我在使用react native时遇到了一些问题,我有点纠结于为什么它不能工作。我正在尝试使用来自react-native-elements的input组件的onChangeText属性来更新朋友页面的状态。
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',
}
});我的问题是,每次我调用函数findFriends()时,我都会得到一个错误,说this.search是未定义的。我试图在渲染期间控制日志this.search,但它似乎停留在未定义的每个渲染周期。我有一种感觉,我应该以某种方式使用道具,但不确定,因为我是相对较新的反应。
编辑:谢谢你的回答,我试着打电话给this.search,尽管它应该是this.state.search,这就是我的代码崩溃的原因。
发布于 2021-01-09 03:18:00
目前还不清楚变量search是否与状态中的变量相同。如果是,则此代码将不起作用。
onChangeText={search =>this.setState({ search})} // setting a state to itself won't work
如果它是一个单独的变量,则您错误地调用了setState。我建议更改变量的名称。setState调用应该看起来更像这样:
onChangeText={ s => this.setState( { search: s } );
search是未定义的(falsey),因为您在您的状态中将其设置为‘’。对于一个基于类的React apporach,你可以使用getDerivedStateFromProps()方法(如果你从属性中传入一个搜索词)。
https://stackoverflow.com/questions/65634775
复制相似问题