【问题标题】:Problem with onChangeText whenn using react-native-component this.setState doesnt set state inside onChangeText使用 react-native-component 时 onChangeText 的问题 this.setState 没有在 onChangeText 内设置状态
【发布时间】:2021-01-08 18:48:55
【问题描述】:

我在使用 react native 时遇到问题,我有点坚持为什么这不起作用。我正在尝试使用来自 react-native-elements 的输入组件的 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 这就是破坏我的代码的原因。

【问题讨论】:

  • 不是this.search,必须是this.state.search。并且您需要将this 绑定到该函数,或者使用箭头函数。 reactjs.org/docs/handling-events.htmlcodepen.io/gaearon/pen/xEmzGg?editors=0010
  • 我尝试将其更改为箭头函数,但似乎不起作用。渲染函数控制台记录状态,每次我在文本框中输入内容时它都是未定义的
  • 你可以尝试将TextInput的值设置为状态,像这样:value={this.state.search}
  • 先设置一个默认值进行测试,然后你就会知道 this.search 不起作用@UğurEren 是对的

标签: javascript react-native setstate


【解决方案1】:

不清楚变量search是否与状态相同。如果是,则此代码将不起作用。

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

如果它是一个单独的变量,则您错误地调用了setState。我建议更改变量的名称。 setState 调用应该看起来更像这样:

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

search 未定义(错误),因为您在您的状态下将其设置为 ' '。对于基于类的 React 方法,您可以使用 getDerivedStateFromProps() 方法(如果您从 props 中传递搜索词)。

【讨论】:

  • 键值对相同​​的情况下,不需要两者都写。
  • 在这种情况下this.setState({ search }); 有效。
猜你喜欢
  • 1970-01-01
  • 2021-07-24
  • 2021-05-27
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 2020-08-16
相关资源
最近更新 更多